nl80211: Clear BSS state mismatches with deauth as a workaround
[libeap.git] / src / drivers / driver_nl80211.c
1 /*
2  * Driver interaction with Linux nl80211/cfg80211
3  * Copyright (c) 2002-2008, 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, Atheros Communications
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * Alternatively, this software may be distributed under the terms of BSD
14  * license.
15  *
16  * See README and COPYING for more details.
17  */
18
19 #include "includes.h"
20 #include <sys/ioctl.h>
21 #include <net/if_arp.h>
22 #include <net/if.h>
23 #include <netlink/genl/genl.h>
24 #include <netlink/genl/family.h>
25 #include <netlink/genl/ctrl.h>
26 #include "nl80211_copy.h"
27
28 #include "common.h"
29 #include "driver.h"
30 #include "eloop.h"
31 #include "common/ieee802_11_defs.h"
32
33 #if defined(CONFIG_AP) || defined(HOSTAPD)
34 #include <netpacket/packet.h>
35 #include <linux/filter.h>
36 #include "radiotap.h"
37 #include "radiotap_iter.h"
38
39 #include "../../hostapd/sta_flags.h"
40 #endif /* CONFIG_AP || HOSTAPD */
41
42 #ifdef CONFIG_LIBNL20
43 /* libnl 2.0 compatibility code */
44 #define nl_handle nl_sock
45 #define nl_handle_alloc_cb nl_socket_alloc_cb
46 #define nl_handle_destroy nl_socket_free
47 #endif /* CONFIG_LIBNL20 */
48
49
50 #ifndef IFF_LOWER_UP
51 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
52 #endif
53 #ifndef IFF_DORMANT
54 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
55 #endif
56
57 #ifndef IF_OPER_DORMANT
58 #define IF_OPER_DORMANT 5
59 #endif
60 #ifndef IF_OPER_UP
61 #define IF_OPER_UP 6
62 #endif
63
64 struct i802_bss {
65         struct i802_bss *next;
66         int ifindex;
67         unsigned int beacon_set:1;
68 };
69
70 struct wpa_driver_nl80211_data {
71         void *ctx;
72         int link_event_sock;
73         int ioctl_sock; /* socket for ioctl() use */
74         char ifname[IFNAMSIZ + 1];
75         int ifindex;
76         int if_removed;
77         struct wpa_driver_capa capa;
78         int has_capability;
79
80         int operstate;
81
82         int scan_complete_events;
83
84         struct nl_handle *nl_handle;
85         struct nl_handle *nl_handle_event;
86         struct nl_cache *nl_cache;
87         struct nl_cache *nl_cache_event;
88         struct nl_cb *nl_cb;
89         struct genl_family *nl80211;
90
91         u8 auth_bssid[ETH_ALEN];
92         u8 bssid[ETH_ALEN];
93         int associated;
94         u8 ssid[32];
95         size_t ssid_len;
96         int nlmode;
97         int ap_scan_as_station;
98
99         int monitor_sock;
100         int monitor_ifidx;
101
102         unsigned int beacon_set:1;
103
104 #ifdef HOSTAPD
105         int eapol_sock; /* socket for EAPOL frames */
106
107         int default_if_indices[16];
108         int *if_indices;
109         int num_if_indices;
110
111         struct i802_bss bss;
112
113         int last_freq;
114         int last_freq_ht;
115 #endif /* HOSTAPD */
116 };
117
118
119 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
120                                             void *timeout_ctx);
121 static int wpa_driver_nl80211_set_mode(void *priv, int mode);
122 static int
123 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
124 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
125                                    const u8 *addr, int cmd, u16 reason_code);
126
127 #if defined(CONFIG_AP) || defined(HOSTAPD)
128 static void nl80211_remove_monitor_interface(
129         struct wpa_driver_nl80211_data *drv);
130 #endif /* CONFIG_AP || HOSTAPD */
131
132 #ifdef CONFIG_AP
133 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
134                                  int ifidx);
135 #endif /* CONFIG_AP */
136
137 #ifdef HOSTAPD
138 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
139 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
140 static struct i802_bss * get_bss(struct wpa_driver_nl80211_data *drv,
141                                  int ifindex);
142 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
143                                  int ifidx);
144 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
145 #endif /* HOSTAPD */
146
147
148 /* nl80211 code */
149 static int ack_handler(struct nl_msg *msg, void *arg)
150 {
151         int *err = arg;
152         *err = 0;
153         return NL_STOP;
154 }
155
156 static int finish_handler(struct nl_msg *msg, void *arg)
157 {
158         int *ret = arg;
159         *ret = 0;
160         return NL_SKIP;
161 }
162
163 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
164                          void *arg)
165 {
166         int *ret = arg;
167         *ret = err->error;
168         return NL_SKIP;
169 }
170
171
172 static int no_seq_check(struct nl_msg *msg, void *arg)
173 {
174         return NL_OK;
175 }
176
177
178 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
179                               struct nl_msg *msg,
180                               int (*valid_handler)(struct nl_msg *, void *),
181                               void *valid_data)
182 {
183         struct nl_cb *cb;
184         int err = -ENOMEM;
185
186         cb = nl_cb_clone(drv->nl_cb);
187         if (!cb)
188                 goto out;
189
190         err = nl_send_auto_complete(drv->nl_handle, msg);
191         if (err < 0)
192                 goto out;
193
194         err = 1;
195
196         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
197         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
198         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
199
200         if (valid_handler)
201                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
202                           valid_handler, valid_data);
203
204         while (err > 0)
205                 nl_recvmsgs(drv->nl_handle, cb);
206  out:
207         nl_cb_put(cb);
208         nlmsg_free(msg);
209         return err;
210 }
211
212
213 struct family_data {
214         const char *group;
215         int id;
216 };
217
218
219 static int family_handler(struct nl_msg *msg, void *arg)
220 {
221         struct family_data *res = arg;
222         struct nlattr *tb[CTRL_ATTR_MAX + 1];
223         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
224         struct nlattr *mcgrp;
225         int i;
226
227         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
228                   genlmsg_attrlen(gnlh, 0), NULL);
229         if (!tb[CTRL_ATTR_MCAST_GROUPS])
230                 return NL_SKIP;
231
232         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
233                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
234                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
235                           nla_len(mcgrp), NULL);
236                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
237                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
238                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
239                                res->group,
240                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
241                         continue;
242                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
243                 break;
244         };
245
246         return NL_SKIP;
247 }
248
249
250 static int nl_get_multicast_id(struct wpa_driver_nl80211_data *drv,
251                                const char *family, const char *group)
252 {
253         struct nl_msg *msg;
254         int ret = -1;
255         struct family_data res = { group, -ENOENT };
256
257         msg = nlmsg_alloc();
258         if (!msg)
259                 return -ENOMEM;
260         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(drv->nl_handle, "nlctrl"),
261                     0, 0, CTRL_CMD_GETFAMILY, 0);
262         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
263
264         ret = send_and_recv_msgs(drv, msg, family_handler, &res);
265         msg = NULL;
266         if (ret == 0)
267                 ret = res.id;
268
269 nla_put_failure:
270         nlmsg_free(msg);
271         return ret;
272 }
273
274
275 #ifdef HOSTAPD
276 static int get_ifhwaddr(struct wpa_driver_nl80211_data *drv,
277                         const char *ifname, u8 *addr)
278 {
279         struct ifreq ifr;
280
281         os_memset(&ifr, 0, sizeof(ifr));
282         os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
283         if (ioctl(drv->ioctl_sock, SIOCGIFHWADDR, &ifr)) {
284                 wpa_printf(MSG_ERROR, "%s: ioctl(SIOCGIFHWADDR): %d (%s)",
285                            ifname, errno, strerror(errno));
286                 return -1;
287         }
288
289         if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
290                 wpa_printf(MSG_ERROR, "%s: Invalid HW-addr family 0x%04x",
291                            ifname, ifr.ifr_hwaddr.sa_family);
292                 return -1;
293         }
294         os_memcpy(addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
295
296         return 0;
297 }
298
299
300 static int set_ifhwaddr(struct wpa_driver_nl80211_data *drv,
301                         const char *ifname, const u8 *addr)
302 {
303         struct ifreq ifr;
304
305         os_memset(&ifr, 0, sizeof(ifr));
306         os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
307         os_memcpy(ifr.ifr_hwaddr.sa_data, addr, ETH_ALEN);
308         ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
309
310         if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifr)) {
311                 wpa_printf(MSG_DEBUG, "%s: ioctl(SIOCSIFHWADDR): %d (%s)",
312                            ifname, errno, strerror(errno));
313                 return -1;
314         }
315
316         return 0;
317 }
318 #endif /* HOSTAPD */
319
320
321 static int wpa_driver_nl80211_send_oper_ifla(
322         struct wpa_driver_nl80211_data *drv,
323         int linkmode, int operstate)
324 {
325         struct {
326                 struct nlmsghdr hdr;
327                 struct ifinfomsg ifinfo;
328                 char opts[16];
329         } req;
330         struct rtattr *rta;
331         static int nl_seq;
332         ssize_t ret;
333
334         os_memset(&req, 0, sizeof(req));
335
336         req.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
337         req.hdr.nlmsg_type = RTM_SETLINK;
338         req.hdr.nlmsg_flags = NLM_F_REQUEST;
339         req.hdr.nlmsg_seq = ++nl_seq;
340         req.hdr.nlmsg_pid = 0;
341
342         req.ifinfo.ifi_family = AF_UNSPEC;
343         req.ifinfo.ifi_type = 0;
344         req.ifinfo.ifi_index = drv->ifindex;
345         req.ifinfo.ifi_flags = 0;
346         req.ifinfo.ifi_change = 0;
347
348         if (linkmode != -1) {
349                 rta = aliasing_hide_typecast(
350                         ((char *) &req + NLMSG_ALIGN(req.hdr.nlmsg_len)),
351                         struct rtattr);
352                 rta->rta_type = IFLA_LINKMODE;
353                 rta->rta_len = RTA_LENGTH(sizeof(char));
354                 *((char *) RTA_DATA(rta)) = linkmode;
355                 req.hdr.nlmsg_len = NLMSG_ALIGN(req.hdr.nlmsg_len) +
356                         RTA_LENGTH(sizeof(char));
357         }
358         if (operstate != -1) {
359                 rta = aliasing_hide_typecast(
360                         ((char *) &req + NLMSG_ALIGN(req.hdr.nlmsg_len)),
361                         struct rtattr);
362                 rta->rta_type = IFLA_OPERSTATE;
363                 rta->rta_len = RTA_LENGTH(sizeof(char));
364                 *((char *) RTA_DATA(rta)) = operstate;
365                 req.hdr.nlmsg_len = NLMSG_ALIGN(req.hdr.nlmsg_len) +
366                         RTA_LENGTH(sizeof(char));
367         }
368
369         wpa_printf(MSG_DEBUG, "nl80211: Operstate: linkmode=%d, operstate=%d",
370                    linkmode, operstate);
371
372         ret = send(drv->link_event_sock, &req, req.hdr.nlmsg_len, 0);
373         if (ret < 0) {
374                 wpa_printf(MSG_DEBUG, "nl80211: Sending operstate IFLA failed:"
375                            " %s (assume operstate is not supported)",
376                            strerror(errno));
377         }
378
379         return ret < 0 ? -1 : 0;
380 }
381
382
383 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
384 {
385         struct wpa_driver_nl80211_data *drv = priv;
386         if (!drv->associated)
387                 return -1;
388         os_memcpy(bssid, drv->bssid, ETH_ALEN);
389         return 0;
390 }
391
392
393 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
394 {
395         struct wpa_driver_nl80211_data *drv = priv;
396         if (!drv->associated)
397                 return -1;
398         os_memcpy(ssid, drv->ssid, drv->ssid_len);
399         return drv->ssid_len;
400 }
401
402
403 #ifndef HOSTAPD
404
405 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
406                                           void *ctx, char *buf, size_t len,
407                                           int del)
408 {
409         union wpa_event_data event;
410
411         os_memset(&event, 0, sizeof(event));
412         if (len > sizeof(event.interface_status.ifname))
413                 len = sizeof(event.interface_status.ifname) - 1;
414         os_memcpy(event.interface_status.ifname, buf, len);
415         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
416                 EVENT_INTERFACE_ADDED;
417
418         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
419                    del ? "DEL" : "NEW",
420                    event.interface_status.ifname,
421                    del ? "removed" : "added");
422
423         if (os_strcmp(drv->ifname, event.interface_status.ifname) == 0) {
424                 if (del)
425                         drv->if_removed = 1;
426                 else
427                         drv->if_removed = 0;
428         }
429
430         wpa_supplicant_event(ctx, EVENT_INTERFACE_STATUS, &event);
431 }
432
433
434 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
435                                          struct nlmsghdr *h)
436 {
437         struct ifinfomsg *ifi;
438         int attrlen, _nlmsg_len, rta_len;
439         struct rtattr *attr;
440
441         ifi = NLMSG_DATA(h);
442
443         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
444
445         attrlen = h->nlmsg_len - _nlmsg_len;
446         if (attrlen < 0)
447                 return 0;
448
449         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
450
451         rta_len = RTA_ALIGN(sizeof(struct rtattr));
452         while (RTA_OK(attr, attrlen)) {
453                 if (attr->rta_type == IFLA_IFNAME) {
454                         if (os_strcmp(((char *) attr) + rta_len, drv->ifname)
455                             == 0)
456                                 return 1;
457                         else
458                                 break;
459                 }
460                 attr = RTA_NEXT(attr, attrlen);
461         }
462
463         return 0;
464 }
465
466
467 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
468                                           int ifindex, struct nlmsghdr *h)
469 {
470         if (drv->ifindex == ifindex)
471                 return 1;
472
473         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, h)) {
474                 drv->ifindex = if_nametoindex(drv->ifname);
475                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
476                            "interface");
477                 wpa_driver_nl80211_finish_drv_init(drv);
478                 return 1;
479         }
480
481         return 0;
482 }
483
484
485 static void wpa_driver_nl80211_event_rtm_newlink(struct wpa_driver_nl80211_data *drv,
486                                               void *ctx, struct nlmsghdr *h,
487                                               size_t len)
488 {
489         struct ifinfomsg *ifi;
490         int attrlen, _nlmsg_len, rta_len;
491         struct rtattr * attr;
492
493         if (len < sizeof(*ifi))
494                 return;
495
496         ifi = NLMSG_DATA(h);
497
498         if (!wpa_driver_nl80211_own_ifindex(drv, ifi->ifi_index, h)) {
499                 wpa_printf(MSG_DEBUG, "Ignore event for foreign ifindex %d",
500                            ifi->ifi_index);
501                 return;
502         }
503
504         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
505                    "(%s%s%s%s)",
506                    drv->operstate, ifi->ifi_flags,
507                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
508                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
509                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
510                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
511         /*
512          * Some drivers send the association event before the operup event--in
513          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
514          * fails. This will hit us when wpa_supplicant does not need to do
515          * IEEE 802.1X authentication
516          */
517         if (drv->operstate == 1 &&
518             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
519             !(ifi->ifi_flags & IFF_RUNNING))
520                 wpa_driver_nl80211_send_oper_ifla(drv, -1, IF_OPER_UP);
521
522         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
523
524         attrlen = h->nlmsg_len - _nlmsg_len;
525         if (attrlen < 0)
526                 return;
527
528         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
529
530         rta_len = RTA_ALIGN(sizeof(struct rtattr));
531         while (RTA_OK(attr, attrlen)) {
532                 if (attr->rta_type == IFLA_IFNAME) {
533                         wpa_driver_nl80211_event_link(
534                                 drv, ctx,
535                                 ((char *) attr) + rta_len,
536                                 attr->rta_len - rta_len, 0);
537                 }
538                 attr = RTA_NEXT(attr, attrlen);
539         }
540 }
541
542
543 static void wpa_driver_nl80211_event_rtm_dellink(struct wpa_driver_nl80211_data *drv,
544                                               void *ctx, struct nlmsghdr *h,
545                                               size_t len)
546 {
547         struct ifinfomsg *ifi;
548         int attrlen, _nlmsg_len, rta_len;
549         struct rtattr * attr;
550
551         if (len < sizeof(*ifi))
552                 return;
553
554         ifi = NLMSG_DATA(h);
555
556         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
557
558         attrlen = h->nlmsg_len - _nlmsg_len;
559         if (attrlen < 0)
560                 return;
561
562         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
563
564         rta_len = RTA_ALIGN(sizeof(struct rtattr));
565         while (RTA_OK(attr, attrlen)) {
566                 if (attr->rta_type == IFLA_IFNAME) {
567                         wpa_driver_nl80211_event_link(
568                                 drv, ctx,
569                                 ((char *) attr) + rta_len,
570                                 attr->rta_len - rta_len, 1);
571                 }
572                 attr = RTA_NEXT(attr, attrlen);
573         }
574 }
575
576
577 static void wpa_driver_nl80211_event_receive_link(int sock, void *eloop_ctx,
578                                                   void *sock_ctx)
579 {
580         char buf[8192];
581         int left;
582         struct sockaddr_nl from;
583         socklen_t fromlen;
584         struct nlmsghdr *h;
585         int max_events = 10;
586
587 try_again:
588         fromlen = sizeof(from);
589         left = recvfrom(sock, buf, sizeof(buf), MSG_DONTWAIT,
590                         (struct sockaddr *) &from, &fromlen);
591         if (left < 0) {
592                 if (errno != EINTR && errno != EAGAIN)
593                         perror("recvfrom(netlink)");
594                 return;
595         }
596
597         h = (struct nlmsghdr *) buf;
598         while (left >= (int) sizeof(*h)) {
599                 int len, plen;
600
601                 len = h->nlmsg_len;
602                 plen = len - sizeof(*h);
603                 if (len > left || plen < 0) {
604                         wpa_printf(MSG_DEBUG, "Malformed netlink message: "
605                                    "len=%d left=%d plen=%d",
606                                    len, left, plen);
607                         break;
608                 }
609
610                 switch (h->nlmsg_type) {
611                 case RTM_NEWLINK:
612                         wpa_driver_nl80211_event_rtm_newlink(eloop_ctx, sock_ctx,
613                                                           h, plen);
614                         break;
615                 case RTM_DELLINK:
616                         wpa_driver_nl80211_event_rtm_dellink(eloop_ctx, sock_ctx,
617                                                           h, plen);
618                         break;
619                 }
620
621                 len = NLMSG_ALIGN(len);
622                 left -= len;
623                 h = (struct nlmsghdr *) ((char *) h + len);
624         }
625
626         if (left > 0) {
627                 wpa_printf(MSG_DEBUG, "%d extra bytes in the end of netlink "
628                            "message", left);
629         }
630
631         if (--max_events > 0) {
632                 /*
633                  * Try to receive all events in one eloop call in order to
634                  * limit race condition on cases where AssocInfo event, Assoc
635                  * event, and EAPOL frames are received more or less at the
636                  * same time. We want to process the event messages first
637                  * before starting EAPOL processing.
638                  */
639                 goto try_again;
640         }
641 }
642
643 #endif /* HOSTAPD */
644
645
646 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
647                             const u8 *frame, size_t len)
648 {
649         const struct ieee80211_mgmt *mgmt;
650         union wpa_event_data event;
651
652         mgmt = (const struct ieee80211_mgmt *) frame;
653         if (len < 24 + sizeof(mgmt->u.auth)) {
654                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
655                            "frame");
656                 return;
657         }
658
659         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
660         os_memset(&event, 0, sizeof(event));
661         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
662         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
663         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
664         if (len > 24 + sizeof(mgmt->u.auth)) {
665                 event.auth.ies = mgmt->u.auth.variable;
666                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
667         }
668
669         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
670 }
671
672
673 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
674                             const u8 *frame, size_t len)
675 {
676         const struct ieee80211_mgmt *mgmt;
677         union wpa_event_data event;
678         u16 status;
679
680         mgmt = (const struct ieee80211_mgmt *) frame;
681         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
682                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
683                            "frame");
684                 return;
685         }
686
687         status = le_to_host16(mgmt->u.assoc_resp.status_code);
688         if (status != WLAN_STATUS_SUCCESS) {
689                 os_memset(&event, 0, sizeof(event));
690                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
691                         event.assoc_reject.resp_ies =
692                                 (u8 *) mgmt->u.assoc_resp.variable;
693                         event.assoc_reject.resp_ies_len =
694                                 len - 24 - sizeof(mgmt->u.assoc_resp);
695                 }
696                 event.assoc_reject.status_code = status;
697
698                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
699                 return;
700         }
701
702         drv->associated = 1;
703         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
704
705         os_memset(&event, 0, sizeof(event));
706         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
707                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
708                 event.assoc_info.resp_ies_len =
709                         len - 24 - sizeof(mgmt->u.assoc_resp);
710         }
711
712         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
713 }
714
715
716 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
717                                enum nl80211_commands cmd, struct nlattr *status,
718                                struct nlattr *addr, struct nlattr *req_ie,
719                                struct nlattr *resp_ie)
720 {
721         union wpa_event_data event;
722
723         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
724                 /*
725                  * Avoid reporting two association events that would confuse
726                  * the core code.
727                  */
728                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
729                            "when using userspace SME", cmd);
730                 return;
731         }
732
733         os_memset(&event, 0, sizeof(event));
734         if (cmd == NL80211_CMD_CONNECT &&
735             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
736                 if (resp_ie) {
737                         event.assoc_reject.resp_ies = nla_data(resp_ie);
738                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
739                 }
740                 event.assoc_reject.status_code = nla_get_u16(status);
741                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
742                 return;
743         }
744
745         drv->associated = 1;
746         if (addr)
747                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
748
749         if (req_ie) {
750                 event.assoc_info.req_ies = nla_data(req_ie);
751                 event.assoc_info.req_ies_len = nla_len(req_ie);
752         }
753         if (resp_ie) {
754                 event.assoc_info.resp_ies = nla_data(resp_ie);
755                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
756         }
757
758         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
759 }
760
761
762 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
763                                enum nl80211_commands cmd, struct nlattr *addr)
764 {
765         union wpa_event_data event;
766         enum wpa_event_type ev;
767
768         if (nla_len(addr) != ETH_ALEN)
769                 return;
770
771         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
772                    cmd, MAC2STR((u8 *) nla_data(addr)));
773
774         if (cmd == NL80211_CMD_AUTHENTICATE)
775                 ev = EVENT_AUTH_TIMED_OUT;
776         else if (cmd == NL80211_CMD_ASSOCIATE)
777                 ev = EVENT_ASSOC_TIMED_OUT;
778         else
779                 return;
780
781         os_memset(&event, 0, sizeof(event));
782         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
783         wpa_supplicant_event(drv->ctx, ev, &event);
784 }
785
786
787 static void mlme_event(struct wpa_driver_nl80211_data *drv,
788                        enum nl80211_commands cmd, struct nlattr *frame,
789                        struct nlattr *addr, struct nlattr *timed_out)
790 {
791         if (timed_out && addr) {
792                 mlme_timeout_event(drv, cmd, addr);
793                 return;
794         }
795
796         if (frame == NULL) {
797                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
798                            "data", cmd);
799                 return;
800         }
801
802         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
803         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
804                     nla_data(frame), nla_len(frame));
805
806         switch (cmd) {
807         case NL80211_CMD_AUTHENTICATE:
808                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
809                 break;
810         case NL80211_CMD_ASSOCIATE:
811                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
812                 break;
813         case NL80211_CMD_DEAUTHENTICATE:
814                 drv->associated = 0;
815                 wpa_supplicant_event(drv->ctx, EVENT_DEAUTH, NULL);
816                 break;
817         case NL80211_CMD_DISASSOCIATE:
818                 drv->associated = 0;
819                 wpa_supplicant_event(drv->ctx, EVENT_DISASSOC, NULL);
820                 break;
821         default:
822                 break;
823         }
824 }
825
826
827 static void mlme_event_michael_mic_failure(struct wpa_driver_nl80211_data *drv,
828                                            struct nlattr *tb[])
829 {
830         union wpa_event_data data;
831
832         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
833         os_memset(&data, 0, sizeof(data));
834         if (tb[NL80211_ATTR_MAC]) {
835                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
836                             nla_data(tb[NL80211_ATTR_MAC]),
837                             nla_len(tb[NL80211_ATTR_MAC]));
838                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
839         }
840         if (tb[NL80211_ATTR_KEY_SEQ]) {
841                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
842                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
843                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
844         }
845         if (tb[NL80211_ATTR_KEY_TYPE]) {
846                 enum nl80211_key_type key_type =
847                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
848                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
849                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
850                         data.michael_mic_failure.unicast = 1;
851         } else
852                 data.michael_mic_failure.unicast = 1;
853
854         if (tb[NL80211_ATTR_KEY_IDX]) {
855                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
856                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
857         }
858
859         wpa_supplicant_event(drv->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
860 }
861
862
863 static int process_event(struct nl_msg *msg, void *arg)
864 {
865         struct wpa_driver_nl80211_data *drv = arg;
866         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
867         struct nlattr *tb[NL80211_ATTR_MAX + 1];
868
869         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
870                   genlmsg_attrlen(gnlh, 0), NULL);
871
872         if (tb[NL80211_ATTR_IFINDEX]) {
873                 int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
874                 if (ifindex != drv->ifindex) {
875                         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
876                                    " for foreign interface (ifindex %d)",
877                                    gnlh->cmd, ifindex);
878                         return NL_SKIP;
879                 }
880         }
881
882         if (drv->ap_scan_as_station &&
883             (gnlh->cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
884              gnlh->cmd == NL80211_CMD_SCAN_ABORTED)) {
885                 wpa_driver_nl80211_set_mode(drv, IEEE80211_MODE_AP);
886                 drv->ap_scan_as_station = 0;
887         }
888
889         switch (gnlh->cmd) {
890         case NL80211_CMD_TRIGGER_SCAN:
891                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
892                 break;
893         case NL80211_CMD_NEW_SCAN_RESULTS:
894                 wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
895                 drv->scan_complete_events = 1;
896                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
897                                      drv->ctx);
898                 wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, NULL);
899                 break;
900         case NL80211_CMD_SCAN_ABORTED:
901                 wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
902                 /*
903                  * Need to indicate that scan results are available in order
904                  * not to make wpa_supplicant stop its scanning.
905                  */
906                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
907                                      drv->ctx);
908                 wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, NULL);
909                 break;
910         case NL80211_CMD_AUTHENTICATE:
911         case NL80211_CMD_ASSOCIATE:
912         case NL80211_CMD_DEAUTHENTICATE:
913         case NL80211_CMD_DISASSOCIATE:
914                 mlme_event(drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
915                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT]);
916                 break;
917         case NL80211_CMD_CONNECT:
918         case NL80211_CMD_ROAM:
919                 mlme_event_connect(drv, gnlh->cmd,
920                                    tb[NL80211_ATTR_STATUS_CODE],
921                                    tb[NL80211_ATTR_MAC],
922                                    tb[NL80211_ATTR_REQ_IE],
923                                    tb[NL80211_ATTR_RESP_IE]);
924                 break;
925         case NL80211_CMD_DISCONNECT:
926                 if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
927                         /*
928                          * Avoid reporting two disassociation events that could
929                          * confuse the core code.
930                          */
931                         wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
932                                    "event when using userspace SME");
933                         break;
934                 }
935                 drv->associated = 0;
936                 wpa_supplicant_event(drv->ctx, EVENT_DISASSOC, NULL);
937                 break;
938         case NL80211_CMD_MICHAEL_MIC_FAILURE:
939                 mlme_event_michael_mic_failure(drv, tb);
940                 break;
941         default:
942                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
943                            "(cmd=%d)", gnlh->cmd);
944                 break;
945         }
946
947         return NL_SKIP;
948 }
949
950
951 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
952                                              void *sock_ctx)
953 {
954         struct nl_cb *cb;
955         struct wpa_driver_nl80211_data *drv = eloop_ctx;
956
957         wpa_printf(MSG_DEBUG, "nl80211: Event message available");
958
959         cb = nl_cb_clone(drv->nl_cb);
960         if (!cb)
961                 return;
962         nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
963         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, process_event, drv);
964         nl_recvmsgs(drv->nl_handle_event, cb);
965         nl_cb_put(cb);
966 }
967
968
969 static int hostapd_set_iface_flags(struct wpa_driver_nl80211_data *drv,
970                                    const char *ifname, int dev_up)
971 {
972         struct ifreq ifr;
973
974         if (drv->ioctl_sock < 0)
975                 return -1;
976
977         os_memset(&ifr, 0, sizeof(ifr));
978         os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
979
980         if (ioctl(drv->ioctl_sock, SIOCGIFFLAGS, &ifr) != 0) {
981                 perror("ioctl[SIOCGIFFLAGS]");
982                 wpa_printf(MSG_DEBUG, "Could not read interface flags (%s)",
983                            ifname);
984                 return -1;
985         }
986
987         if (dev_up) {
988                 if (ifr.ifr_flags & IFF_UP)
989                         return 0;
990                 ifr.ifr_flags |= IFF_UP;
991         } else {
992                 if (!(ifr.ifr_flags & IFF_UP))
993                         return 0;
994                 ifr.ifr_flags &= ~IFF_UP;
995         }
996
997         if (ioctl(drv->ioctl_sock, SIOCSIFFLAGS, &ifr) != 0) {
998                 perror("ioctl[SIOCSIFFLAGS]");
999                 return -1;
1000         }
1001
1002         return 0;
1003 }
1004
1005
1006 /**
1007  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
1008  * @priv: driver_nl80211 private data
1009  * @alpha2_arg: country to which to switch to
1010  * Returns: 0 on success, -1 on failure
1011  *
1012  * This asks nl80211 to set the regulatory domain for given
1013  * country ISO / IEC alpha2.
1014  */
1015 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
1016 {
1017         struct wpa_driver_nl80211_data *drv = priv;
1018         char alpha2[3];
1019         struct nl_msg *msg;
1020
1021         msg = nlmsg_alloc();
1022         if (!msg)
1023                 return -ENOMEM;
1024
1025         alpha2[0] = alpha2_arg[0];
1026         alpha2[1] = alpha2_arg[1];
1027         alpha2[2] = '\0';
1028
1029         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1030                     0, NL80211_CMD_REQ_SET_REG, 0);
1031
1032         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
1033         if (send_and_recv_msgs(drv, msg, NULL, NULL))
1034                 return -EINVAL;
1035         return 0;
1036 nla_put_failure:
1037         return -EINVAL;
1038 }
1039
1040
1041 #ifndef HOSTAPD
1042 struct wiphy_info_data {
1043         int max_scan_ssids;
1044         int ap_supported;
1045         int auth_supported;
1046         int connect_supported;
1047 };
1048
1049
1050 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
1051 {
1052         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1053         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1054         struct wiphy_info_data *info = arg;
1055
1056         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1057                   genlmsg_attrlen(gnlh, 0), NULL);
1058
1059         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
1060                 info->max_scan_ssids =
1061                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
1062
1063         if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
1064                 struct nlattr *nl_mode;
1065                 int i;
1066                 nla_for_each_nested(nl_mode,
1067                                     tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
1068                         if (nl_mode->nla_type == NL80211_IFTYPE_AP) {
1069                                 info->ap_supported = 1;
1070                                 break;
1071                         }
1072                 }
1073         }
1074
1075         if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
1076                 struct nlattr *nl_cmd;
1077                 int i;
1078
1079                 nla_for_each_nested(nl_cmd,
1080                                     tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
1081                         u32 cmd = nla_get_u32(nl_cmd);
1082                         if (cmd == NL80211_CMD_AUTHENTICATE)
1083                                 info->auth_supported = 1;
1084                         else if (cmd == NL80211_CMD_CONNECT)
1085                                 info->connect_supported = 1;
1086                 }
1087         }
1088
1089         return NL_SKIP;
1090 }
1091
1092
1093 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
1094                                        struct wiphy_info_data *info)
1095 {
1096         struct nl_msg *msg;
1097
1098         os_memset(info, 0, sizeof(*info));
1099         msg = nlmsg_alloc();
1100         if (!msg)
1101                 return -1;
1102
1103         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1104                     0, NL80211_CMD_GET_WIPHY, 0);
1105
1106         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1107
1108         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
1109                 return 0;
1110         msg = NULL;
1111 nla_put_failure:
1112         nlmsg_free(msg);
1113         return -1;
1114 }
1115
1116
1117 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
1118 {
1119         struct wiphy_info_data info;
1120         if (wpa_driver_nl80211_get_info(drv, &info))
1121                 return -1;
1122         drv->has_capability = 1;
1123         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
1124         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
1125                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
1126                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
1127                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
1128         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
1129                 WPA_DRIVER_CAPA_ENC_WEP104 |
1130                 WPA_DRIVER_CAPA_ENC_TKIP |
1131                 WPA_DRIVER_CAPA_ENC_CCMP;
1132
1133         drv->capa.max_scan_ssids = info.max_scan_ssids;
1134         if (info.ap_supported)
1135                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP;
1136
1137         if (info.auth_supported)
1138                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
1139         else if (!info.connect_supported) {
1140                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
1141                            "authentication/association or connect commands");
1142                 return -1;
1143         }
1144
1145         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
1146
1147         return 0;
1148 }
1149 #endif /* HOSTAPD */
1150
1151
1152 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv,
1153                                       void *ctx)
1154 {
1155         int ret;
1156
1157         /* Initialize generic netlink and nl80211 */
1158
1159         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
1160         if (drv->nl_cb == NULL) {
1161                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1162                            "callbacks");
1163                 goto err1;
1164         }
1165
1166         drv->nl_handle = nl_handle_alloc_cb(drv->nl_cb);
1167         if (drv->nl_handle == NULL) {
1168                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1169                            "callbacks");
1170                 goto err2;
1171         }
1172
1173         drv->nl_handle_event = nl_handle_alloc_cb(drv->nl_cb);
1174         if (drv->nl_handle_event == NULL) {
1175                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1176                            "callbacks (event)");
1177                 goto err2b;
1178         }
1179
1180         if (genl_connect(drv->nl_handle)) {
1181                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1182                            "netlink");
1183                 goto err3;
1184         }
1185
1186         if (genl_connect(drv->nl_handle_event)) {
1187                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1188                            "netlink (event)");
1189                 goto err3;
1190         }
1191
1192 #ifdef CONFIG_LIBNL20
1193         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
1194                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1195                            "netlink cache");
1196                 goto err3;
1197         }
1198         if (genl_ctrl_alloc_cache(drv->nl_handle_event, &drv->nl_cache_event) <
1199             0) {
1200                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1201                            "netlink cache (event)");
1202                 goto err3b;
1203         }
1204 #else /* CONFIG_LIBNL20 */
1205         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
1206         if (drv->nl_cache == NULL) {
1207                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1208                            "netlink cache");
1209                 goto err3;
1210         }
1211         drv->nl_cache_event = genl_ctrl_alloc_cache(drv->nl_handle_event);
1212         if (drv->nl_cache_event == NULL) {
1213                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1214                            "netlink cache (event)");
1215                 goto err3b;
1216         }
1217 #endif /* CONFIG_LIBNL20 */
1218
1219         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
1220         if (drv->nl80211 == NULL) {
1221                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
1222                            "found");
1223                 goto err4;
1224         }
1225
1226         ret = nl_get_multicast_id(drv, "nl80211", "scan");
1227         if (ret >= 0)
1228                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1229         if (ret < 0) {
1230                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1231                            "membership for scan events: %d (%s)",
1232                            ret, strerror(-ret));
1233                 goto err4;
1234         }
1235
1236         ret = nl_get_multicast_id(drv, "nl80211", "mlme");
1237         if (ret >= 0)
1238                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1239         if (ret < 0) {
1240                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1241                            "membership for mlme events: %d (%s)",
1242                            ret, strerror(-ret));
1243                 goto err4;
1244         }
1245
1246         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_event),
1247                                  wpa_driver_nl80211_event_receive, drv, ctx);
1248
1249         return 0;
1250
1251 err4:
1252         nl_cache_free(drv->nl_cache_event);
1253 err3b:
1254         nl_cache_free(drv->nl_cache);
1255 err3:
1256         nl_handle_destroy(drv->nl_handle_event);
1257 err2b:
1258         nl_handle_destroy(drv->nl_handle);
1259 err2:
1260         nl_cb_put(drv->nl_cb);
1261 err1:
1262         return -1;
1263 }
1264
1265
1266 static int wpa_driver_nl80211_init_link_events(
1267         struct wpa_driver_nl80211_data *drv)
1268 {
1269 #ifdef HOSTAPD
1270         return 0;
1271 #else /* HOSTAPD */
1272         int s;
1273         struct sockaddr_nl local;
1274
1275         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1276         if (s < 0) {
1277                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
1278                 return -1;
1279         }
1280
1281         os_memset(&local, 0, sizeof(local));
1282         local.nl_family = AF_NETLINK;
1283         local.nl_groups = RTMGRP_LINK;
1284         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
1285                 perror("bind(netlink)");
1286                 close(s);
1287                 return -1;
1288         }
1289
1290         eloop_register_read_sock(s, wpa_driver_nl80211_event_receive_link, drv,
1291                                  drv->ctx);
1292         drv->link_event_sock = s;
1293
1294         return 0;
1295 #endif /* HOSTAPD */
1296 }
1297
1298
1299 /**
1300  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
1301  * @ctx: context to be used when calling wpa_supplicant functions,
1302  * e.g., wpa_supplicant_event()
1303  * @ifname: interface name, e.g., wlan0
1304  * Returns: Pointer to private data, %NULL on failure
1305  */
1306 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname)
1307 {
1308         struct wpa_driver_nl80211_data *drv;
1309
1310         drv = os_zalloc(sizeof(*drv));
1311         if (drv == NULL)
1312                 return NULL;
1313         drv->ctx = ctx;
1314         os_strlcpy(drv->ifname, ifname, sizeof(drv->ifname));
1315         drv->monitor_ifidx = -1;
1316         drv->monitor_sock = -1;
1317         drv->link_event_sock = -1;
1318         drv->ioctl_sock = -1;
1319
1320         if (wpa_driver_nl80211_init_nl(drv, ctx)) {
1321                 os_free(drv);
1322                 return NULL;
1323         }
1324
1325         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
1326         if (drv->ioctl_sock < 0) {
1327                 perror("socket(PF_INET,SOCK_DGRAM)");
1328                 goto failed;
1329         }
1330
1331         if (wpa_driver_nl80211_init_link_events(drv) ||
1332             wpa_driver_nl80211_finish_drv_init(drv))
1333                 goto failed;
1334
1335         return drv;
1336
1337 failed:
1338         if (drv->link_event_sock >= 0) {
1339                 eloop_unregister_read_sock(drv->link_event_sock);
1340                 close(drv->link_event_sock);
1341         }
1342         if (drv->ioctl_sock >= 0)
1343                 close(drv->ioctl_sock);
1344
1345         genl_family_put(drv->nl80211);
1346         nl_cache_free(drv->nl_cache);
1347         nl_handle_destroy(drv->nl_handle);
1348         nl_cb_put(drv->nl_cb);
1349
1350         os_free(drv);
1351         return NULL;
1352 }
1353
1354
1355 static int
1356 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
1357 {
1358         drv->ifindex = if_nametoindex(drv->ifname);
1359
1360 #ifndef HOSTAPD
1361         if (wpa_driver_nl80211_set_mode(drv, IEEE80211_MODE_INFRA) < 0) {
1362                 wpa_printf(MSG_DEBUG, "nl80211: Could not configure driver to "
1363                            "use managed mode");
1364         }
1365
1366         if (hostapd_set_iface_flags(drv, drv->ifname, 1)) {
1367                 wpa_printf(MSG_ERROR, "Could not set interface '%s' "
1368                            "UP", drv->ifname);
1369                 return -1;
1370         }
1371
1372         if (wpa_driver_nl80211_capa(drv))
1373                 return -1;
1374
1375         wpa_driver_nl80211_send_oper_ifla(drv, 1, IF_OPER_DORMANT);
1376 #endif /* HOSTAPD */
1377
1378         return 0;
1379 }
1380
1381
1382 #ifdef HOSTAPD
1383 static void wpa_driver_nl80211_free_bss(struct wpa_driver_nl80211_data *drv)
1384 {
1385         struct i802_bss *bss, *prev;
1386         bss = drv->bss.next;
1387         while (bss) {
1388                 prev = bss;
1389                 bss = bss->next;
1390                 os_free(bss);
1391         }
1392 }
1393 #endif /* HOSTAPD */
1394
1395
1396 #if defined(CONFIG_AP) || defined(HOSTAPD)
1397 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
1398 {
1399         struct nl_msg *msg;
1400
1401         msg = nlmsg_alloc();
1402         if (!msg)
1403                 return -ENOMEM;
1404
1405         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1406                     0, NL80211_CMD_DEL_BEACON, 0);
1407         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1408
1409         return send_and_recv_msgs(drv, msg, NULL, NULL);
1410  nla_put_failure:
1411         return -ENOBUFS;
1412 }
1413 #endif /* CONFIG_AP || HOSTAPD */
1414
1415
1416 /**
1417  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
1418  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
1419  *
1420  * Shut down driver interface and processing of driver events. Free
1421  * private data buffer if one was allocated in wpa_driver_nl80211_init().
1422  */
1423 static void wpa_driver_nl80211_deinit(void *priv)
1424 {
1425         struct wpa_driver_nl80211_data *drv = priv;
1426
1427 #if defined(CONFIG_AP) || defined(HOSTAPD)
1428         nl80211_remove_monitor_interface(drv);
1429         if (drv->monitor_sock >= 0) {
1430                 eloop_unregister_read_sock(drv->monitor_sock);
1431                 close(drv->monitor_sock);
1432         }
1433
1434         if (drv->nlmode == NL80211_IFTYPE_AP)
1435                 wpa_driver_nl80211_del_beacon(drv);
1436 #endif /* CONFIG_AP || HOSTAPD */
1437
1438 #ifdef HOSTAPD
1439         if (drv->last_freq_ht) {
1440                 /* Clear HT flags from the driver */
1441                 struct hostapd_freq_params freq;
1442                 os_memset(&freq, 0, sizeof(freq));
1443                 freq.freq = drv->last_freq;
1444                 i802_set_freq(priv, &freq);
1445         }
1446
1447         if (drv->eapol_sock >= 0) {
1448                 eloop_unregister_read_sock(drv->eapol_sock);
1449                 close(drv->eapol_sock);
1450         }
1451
1452         if (drv->if_indices != drv->default_if_indices)
1453                 os_free(drv->if_indices);
1454
1455         wpa_driver_nl80211_free_bss(drv);
1456 #else /* HOSTAPD */
1457
1458         wpa_driver_nl80211_send_oper_ifla(priv, 0, IF_OPER_UP);
1459
1460         if (drv->link_event_sock >= 0) {
1461                 eloop_unregister_read_sock(drv->link_event_sock);
1462                 close(drv->link_event_sock);
1463         }
1464 #endif /* HOSTAPD */
1465
1466         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
1467
1468         (void) hostapd_set_iface_flags(drv, drv->ifname, 0);
1469         wpa_driver_nl80211_set_mode(drv, IEEE80211_MODE_INFRA);
1470
1471         if (drv->ioctl_sock >= 0)
1472                 close(drv->ioctl_sock);
1473
1474         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
1475         genl_family_put(drv->nl80211);
1476         nl_cache_free(drv->nl_cache);
1477         nl_cache_free(drv->nl_cache_event);
1478         nl_handle_destroy(drv->nl_handle);
1479         nl_handle_destroy(drv->nl_handle_event);
1480         nl_cb_put(drv->nl_cb);
1481
1482         os_free(drv);
1483 }
1484
1485
1486 /**
1487  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
1488  * @eloop_ctx: Driver private data
1489  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
1490  *
1491  * This function can be used as registered timeout when starting a scan to
1492  * generate a scan completed event if the driver does not report this.
1493  */
1494 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
1495 {
1496         struct wpa_driver_nl80211_data *drv = eloop_ctx;
1497         if (drv->ap_scan_as_station) {
1498                 wpa_driver_nl80211_set_mode(drv, IEEE80211_MODE_AP);
1499                 drv->ap_scan_as_station = 0;
1500         }
1501         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
1502         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
1503 }
1504
1505
1506 /**
1507  * wpa_driver_nl80211_scan - Request the driver to initiate scan
1508  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
1509  * @params: Scan parameters
1510  * Returns: 0 on success, -1 on failure
1511  */
1512 static int wpa_driver_nl80211_scan(void *priv,
1513                                    struct wpa_driver_scan_params *params)
1514 {
1515         struct wpa_driver_nl80211_data *drv = priv;
1516         int ret = 0, timeout;
1517         struct nl_msg *msg, *ssids, *freqs;
1518         size_t i;
1519
1520         msg = nlmsg_alloc();
1521         ssids = nlmsg_alloc();
1522         freqs = nlmsg_alloc();
1523         if (!msg || !ssids || !freqs) {
1524                 nlmsg_free(msg);
1525                 nlmsg_free(ssids);
1526                 nlmsg_free(freqs);
1527                 return -1;
1528         }
1529
1530         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1531                     NL80211_CMD_TRIGGER_SCAN, 0);
1532
1533         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1534
1535         for (i = 0; i < params->num_ssids; i++) {
1536                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
1537                         params->ssids[i].ssid);
1538         }
1539         if (params->num_ssids)
1540                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
1541
1542         if (params->extra_ies) {
1543                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
1544                         params->extra_ies);
1545         }
1546
1547         if (params->freqs) {
1548                 for (i = 0; params->freqs[i]; i++)
1549                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
1550                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
1551         }
1552
1553         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1554         msg = NULL;
1555         if (ret) {
1556                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
1557                            "(%s)", ret, strerror(-ret));
1558 #ifdef HOSTAPD
1559                 if (drv->nlmode == NL80211_IFTYPE_AP) {
1560                         /*
1561                          * mac80211 does not allow scan requests in AP mode, so
1562                          * try to do this in station mode.
1563                          */
1564                         if (wpa_driver_nl80211_set_mode(drv,
1565                                                         IEEE80211_MODE_INFRA))
1566                                 goto nla_put_failure;
1567
1568                         if (wpa_driver_nl80211_scan(drv, params)) {
1569                                 wpa_driver_nl80211_set_mode(drv,
1570                                                             IEEE80211_MODE_AP);
1571                                 goto nla_put_failure;
1572                         }
1573
1574                         /* Restore AP mode when processing scan results */
1575                         drv->ap_scan_as_station = 1;
1576                         ret = 0;
1577                 } else
1578                         goto nla_put_failure;
1579 #else /* HOSTAPD */
1580                 goto nla_put_failure;
1581 #endif /* HOSTAPD */
1582         }
1583
1584         /* Not all drivers generate "scan completed" wireless event, so try to
1585          * read results after a timeout. */
1586         timeout = 10;
1587         if (drv->scan_complete_events) {
1588                 /*
1589                  * The driver seems to deliver events to notify when scan is
1590                  * complete, so use longer timeout to avoid race conditions
1591                  * with scanning and following association request.
1592                  */
1593                 timeout = 30;
1594         }
1595         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
1596                    "seconds", ret, timeout);
1597         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
1598         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
1599                                drv, drv->ctx);
1600
1601 nla_put_failure:
1602         nlmsg_free(ssids);
1603         nlmsg_free(msg);
1604         nlmsg_free(freqs);
1605         return ret;
1606 }
1607
1608
1609 static int bss_info_handler(struct nl_msg *msg, void *arg)
1610 {
1611         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1612         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1613         struct nlattr *bss[NL80211_BSS_MAX + 1];
1614         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1615                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
1616                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
1617                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
1618                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
1619                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
1620                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
1621                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
1622                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
1623                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
1624                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
1625         };
1626         struct wpa_scan_results *res = arg;
1627         struct wpa_scan_res **tmp;
1628         struct wpa_scan_res *r;
1629         const u8 *ie;
1630         size_t ie_len;
1631
1632         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1633                   genlmsg_attrlen(gnlh, 0), NULL);
1634         if (!tb[NL80211_ATTR_BSS])
1635                 return NL_SKIP;
1636         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
1637                              bss_policy))
1638                 return NL_SKIP;
1639         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
1640                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1641                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1642         } else {
1643                 ie = NULL;
1644                 ie_len = 0;
1645         }
1646
1647         r = os_zalloc(sizeof(*r) + ie_len);
1648         if (r == NULL)
1649                 return NL_SKIP;
1650         if (bss[NL80211_BSS_BSSID])
1651                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
1652                           ETH_ALEN);
1653         if (bss[NL80211_BSS_FREQUENCY])
1654                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
1655         if (bss[NL80211_BSS_BEACON_INTERVAL])
1656                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
1657         if (bss[NL80211_BSS_CAPABILITY])
1658                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
1659         r->flags |= WPA_SCAN_NOISE_INVALID;
1660         if (bss[NL80211_BSS_SIGNAL_MBM]) {
1661                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
1662                 r->level /= 100; /* mBm to dBm */
1663                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
1664         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
1665                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
1666                 r->flags |= WPA_SCAN_LEVEL_INVALID;
1667         } else
1668                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
1669         if (bss[NL80211_BSS_TSF])
1670                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
1671         if (bss[NL80211_BSS_SEEN_MS_AGO])
1672                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
1673         r->ie_len = ie_len;
1674         if (ie)
1675                 os_memcpy(r + 1, ie, ie_len);
1676
1677         if (bss[NL80211_BSS_STATUS]) {
1678                 enum nl80211_bss_status status;
1679                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
1680                 switch (status) {
1681                 case NL80211_BSS_STATUS_AUTHENTICATED:
1682                         r->flags |= WPA_SCAN_AUTHENTICATED;
1683                         break;
1684                 case NL80211_BSS_STATUS_ASSOCIATED:
1685                         r->flags |= WPA_SCAN_ASSOCIATED;
1686                         break;
1687                 default:
1688                         break;
1689                 }
1690         }
1691
1692         tmp = os_realloc(res->res,
1693                          (res->num + 1) * sizeof(struct wpa_scan_res *));
1694         if (tmp == NULL) {
1695                 os_free(r);
1696                 return NL_SKIP;
1697         }
1698         tmp[res->num++] = r;
1699         res->res = tmp;
1700
1701         return NL_SKIP;
1702 }
1703
1704
1705 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
1706                                  const u8 *addr)
1707 {
1708         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1709                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
1710                            "mismatch");
1711                 wpa_driver_nl80211_mlme(drv, addr,
1712                                         NL80211_CMD_DEAUTHENTICATE,
1713                                         WLAN_REASON_PREV_AUTH_NOT_VALID);
1714         }
1715 }
1716
1717
1718 static void wpa_driver_nl80211_check_bss_status(
1719         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
1720 {
1721         size_t i;
1722
1723         for (i = 0; i < res->num; i++) {
1724                 struct wpa_scan_res *r = res->res[i];
1725                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
1726                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
1727                                    "indicates BSS status with " MACSTR
1728                                    " as authenticated",
1729                                    MAC2STR(r->bssid));
1730                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
1731                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
1732                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
1733                             0) {
1734                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
1735                                            " in local state (auth=" MACSTR
1736                                            " assoc=" MACSTR ")",
1737                                            MAC2STR(drv->auth_bssid),
1738                                            MAC2STR(drv->bssid));
1739                         }
1740                 }
1741
1742                 if (r->flags & WPA_SCAN_ASSOCIATED) {
1743                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
1744                                    "indicate BSS status with " MACSTR
1745                                    " as associated",
1746                                    MAC2STR(r->bssid));
1747                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
1748                             !drv->associated) {
1749                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
1750                                            "(not associated) does not match "
1751                                            "with BSS state");
1752                                 clear_state_mismatch(drv, r->bssid);
1753                         } else if (drv->nlmode == NL80211_IFTYPE_STATION &&
1754                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
1755                                    0) {
1756                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
1757                                            "(associated with " MACSTR ") does "
1758                                            "not match with BSS state",
1759                                            MAC2STR(drv->bssid));
1760                                 clear_state_mismatch(drv, r->bssid);
1761                                 clear_state_mismatch(drv, drv->bssid);
1762                         }
1763                 }
1764         }
1765 }
1766
1767
1768 /**
1769  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
1770  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
1771  * Returns: Scan results on success, -1 on failure
1772  */
1773 static struct wpa_scan_results *
1774 wpa_driver_nl80211_get_scan_results(void *priv)
1775 {
1776         struct wpa_driver_nl80211_data *drv = priv;
1777         struct nl_msg *msg;
1778         struct wpa_scan_results *res;
1779         int ret;
1780
1781         res = os_zalloc(sizeof(*res));
1782         if (res == NULL)
1783                 return NULL;
1784         msg = nlmsg_alloc();
1785         if (!msg)
1786                 goto nla_put_failure;
1787
1788         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
1789                     NL80211_CMD_GET_SCAN, 0);
1790         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1791
1792         ret = send_and_recv_msgs(drv, msg, bss_info_handler, res);
1793         msg = NULL;
1794         if (ret == 0) {
1795                 wpa_printf(MSG_DEBUG, "Received scan results (%lu BSSes)",
1796                            (unsigned long) res->num);
1797                 wpa_driver_nl80211_check_bss_status(drv, res);
1798                 return res;
1799         }
1800         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1801                    "(%s)", ret, strerror(-ret));
1802 nla_put_failure:
1803         nlmsg_free(msg);
1804         wpa_scan_results_free(res);
1805         return NULL;
1806 }
1807
1808
1809 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
1810                                       wpa_alg alg, const u8 *addr, int key_idx,
1811                                       int set_tx,
1812                                       const u8 *seq, size_t seq_len,
1813                                       const u8 *key, size_t key_len)
1814 {
1815         struct wpa_driver_nl80211_data *drv = priv;
1816         int ifindex = if_nametoindex(ifname);
1817         struct nl_msg *msg;
1818         int ret;
1819
1820         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
1821                    "set_tx=%d seq_len=%lu key_len=%lu",
1822                    __func__, ifindex, alg, addr, key_idx, set_tx,
1823                    (unsigned long) seq_len, (unsigned long) key_len);
1824
1825         msg = nlmsg_alloc();
1826         if (!msg)
1827                 return -ENOMEM;
1828
1829         if (alg == WPA_ALG_NONE) {
1830                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1831                             0, NL80211_CMD_DEL_KEY, 0);
1832         } else {
1833                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1834                             0, NL80211_CMD_NEW_KEY, 0);
1835                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
1836                 switch (alg) {
1837                 case WPA_ALG_WEP:
1838                         if (key_len == 5)
1839                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1840                                             WLAN_CIPHER_SUITE_WEP40);
1841                         else
1842                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1843                                             WLAN_CIPHER_SUITE_WEP104);
1844                         break;
1845                 case WPA_ALG_TKIP:
1846                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1847                                     WLAN_CIPHER_SUITE_TKIP);
1848                         break;
1849                 case WPA_ALG_CCMP:
1850                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1851                                     WLAN_CIPHER_SUITE_CCMP);
1852                         break;
1853                 case WPA_ALG_IGTK:
1854                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1855                                     WLAN_CIPHER_SUITE_AES_CMAC);
1856                         break;
1857                 default:
1858                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
1859                                    "algorithm %d", __func__, alg);
1860                         nlmsg_free(msg);
1861                         return -1;
1862                 }
1863         }
1864
1865         if (seq && seq_len)
1866                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
1867
1868         if (addr && os_memcmp(addr, "\xff\xff\xff\xff\xff\xff", ETH_ALEN) != 0)
1869         {
1870                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
1871                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
1872         }
1873         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
1874         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
1875
1876         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1877         if (ret == -ENOENT && alg == WPA_ALG_NONE)
1878                 ret = 0;
1879         if (ret)
1880                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
1881                            ret, strerror(-ret));
1882
1883         /*
1884          * If we failed or don't need to set the default TX key (below),
1885          * we're done here.
1886          */
1887         if (ret || !set_tx || alg == WPA_ALG_NONE)
1888                 return ret;
1889 #ifdef HOSTAPD /* FIX: is this needed? */
1890         if (addr)
1891                 return ret;
1892 #endif /* HOSTAPD */
1893
1894         msg = nlmsg_alloc();
1895         if (!msg)
1896                 return -ENOMEM;
1897
1898         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1899                     0, NL80211_CMD_SET_KEY, 0);
1900         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
1901         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
1902         if (alg == WPA_ALG_IGTK)
1903                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
1904         else
1905                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
1906
1907         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1908         if (ret == -ENOENT)
1909                 ret = 0;
1910         if (ret)
1911                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
1912                            "err=%d %s)", ret, strerror(-ret));
1913         return ret;
1914
1915 nla_put_failure:
1916         return -ENOBUFS;
1917 }
1918
1919
1920 static int nl_add_key(struct nl_msg *msg, wpa_alg alg,
1921                       int key_idx, int defkey,
1922                       const u8 *seq, size_t seq_len,
1923                       const u8 *key, size_t key_len)
1924 {
1925         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
1926         if (!key_attr)
1927                 return -1;
1928
1929         if (defkey && alg == WPA_ALG_IGTK)
1930                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
1931         else if (defkey)
1932                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
1933
1934         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
1935
1936         switch (alg) {
1937         case WPA_ALG_WEP:
1938                 if (key_len == 5)
1939                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
1940                                     WLAN_CIPHER_SUITE_WEP40);
1941                 else
1942                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
1943                                     WLAN_CIPHER_SUITE_WEP104);
1944                 break;
1945         case WPA_ALG_TKIP:
1946                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
1947                 break;
1948         case WPA_ALG_CCMP:
1949                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
1950                 break;
1951         case WPA_ALG_IGTK:
1952                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
1953                             WLAN_CIPHER_SUITE_AES_CMAC);
1954                 break;
1955         default:
1956                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
1957                            "algorithm %d", __func__, alg);
1958                 return -1;
1959         }
1960
1961         if (seq && seq_len)
1962                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
1963
1964         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
1965
1966         nla_nest_end(msg, key_attr);
1967
1968         return 0;
1969  nla_put_failure:
1970         return -1;
1971 }
1972
1973
1974 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
1975                                  struct nl_msg *msg)
1976 {
1977         int i, privacy = 0;
1978         struct nlattr *nl_keys, *nl_key;
1979
1980         for (i = 0; i < 4; i++) {
1981                 if (!params->wep_key[i])
1982                         continue;
1983                 privacy = 1;
1984                 break;
1985         }
1986         if (!privacy)
1987                 return 0;
1988
1989         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
1990
1991         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
1992         if (!nl_keys)
1993                 goto nla_put_failure;
1994
1995         for (i = 0; i < 4; i++) {
1996                 if (!params->wep_key[i])
1997                         continue;
1998
1999                 nl_key = nla_nest_start(msg, i);
2000                 if (!nl_key)
2001                         goto nla_put_failure;
2002
2003                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
2004                         params->wep_key[i]);
2005                 if (params->wep_key_len[i] == 5)
2006                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2007                                     WLAN_CIPHER_SUITE_WEP40);
2008                 else
2009                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2010                                     WLAN_CIPHER_SUITE_WEP104);
2011
2012                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
2013
2014                 if (i == params->wep_tx_keyidx)
2015                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2016
2017                 nla_nest_end(msg, nl_key);
2018         }
2019         nla_nest_end(msg, nl_keys);
2020
2021         return 0;
2022
2023 nla_put_failure:
2024         return -ENOBUFS;
2025 }
2026
2027
2028 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
2029                                    const u8 *addr, int cmd, u16 reason_code)
2030 {
2031         int ret = -1;
2032         struct nl_msg *msg;
2033
2034         msg = nlmsg_alloc();
2035         if (!msg)
2036                 return -1;
2037
2038         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0, cmd, 0);
2039
2040         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2041         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
2042         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2043
2044         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2045         msg = NULL;
2046         if (ret) {
2047                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
2048                            "(%s)", ret, strerror(-ret));
2049                 goto nla_put_failure;
2050         }
2051         ret = 0;
2052
2053 nla_put_failure:
2054         nlmsg_free(msg);
2055         return ret;
2056 }
2057
2058
2059 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
2060                                          const u8 *addr, int reason_code)
2061 {
2062         wpa_printf(MSG_DEBUG, "%s", __func__);
2063         drv->associated = 0;
2064         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
2065                                        reason_code);
2066 }
2067
2068
2069 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
2070                                              int reason_code)
2071 {
2072         struct wpa_driver_nl80211_data *drv = priv;
2073         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
2074                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
2075         wpa_printf(MSG_DEBUG, "%s", __func__);
2076         drv->associated = 0;
2077         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
2078                                        reason_code);
2079 }
2080
2081
2082 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
2083                                            int reason_code)
2084 {
2085         struct wpa_driver_nl80211_data *drv = priv;
2086         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
2087                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
2088         wpa_printf(MSG_DEBUG, "%s", __func__);
2089         drv->associated = 0;
2090         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
2091                                        reason_code);
2092 }
2093
2094
2095 static int wpa_driver_nl80211_authenticate(
2096         void *priv, struct wpa_driver_auth_params *params)
2097 {
2098         struct wpa_driver_nl80211_data *drv = priv;
2099         int ret = -1, i;
2100         struct nl_msg *msg;
2101         enum nl80211_auth_type type;
2102         int count = 0;
2103
2104         drv->associated = 0;
2105         os_memset(drv->auth_bssid, 0, ETH_ALEN);
2106
2107         if (wpa_driver_nl80211_set_mode(drv, IEEE80211_MODE_INFRA) < 0)
2108                 return -1;
2109
2110 retry:
2111         msg = nlmsg_alloc();
2112         if (!msg)
2113                 return -1;
2114
2115         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
2116                    drv->ifindex);
2117
2118         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2119                     NL80211_CMD_AUTHENTICATE, 0);
2120
2121         for (i = 0; i < 4; i++) {
2122                 if (!params->wep_key[i])
2123                         continue;
2124                 wpa_driver_nl80211_set_key(drv->ifname, drv, WPA_ALG_WEP, NULL,
2125                                            i,
2126                                            i == params->wep_tx_keyidx, NULL, 0,
2127                                            params->wep_key[i],
2128                                            params->wep_key_len[i]);
2129                 if (params->wep_tx_keyidx != i)
2130                         continue;
2131                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
2132                                params->wep_key[i], params->wep_key_len[i])) {
2133                         nlmsg_free(msg);
2134                         return -1;
2135                 }
2136         }
2137
2138         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2139         if (params->bssid) {
2140                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
2141                            MAC2STR(params->bssid));
2142                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
2143         }
2144         if (params->freq) {
2145                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
2146                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
2147         }
2148         if (params->ssid) {
2149                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
2150                                   params->ssid, params->ssid_len);
2151                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
2152                         params->ssid);
2153         }
2154         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
2155         if (params->ie)
2156                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
2157         /*
2158          * TODO: if multiple auth_alg options enabled, try them one by one if
2159          * the AP rejects authentication due to unknown auth alg
2160          */
2161         if (params->auth_alg & AUTH_ALG_OPEN_SYSTEM)
2162                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
2163         else if (params->auth_alg & AUTH_ALG_SHARED_KEY)
2164                 type = NL80211_AUTHTYPE_SHARED_KEY;
2165         else if (params->auth_alg & AUTH_ALG_LEAP)
2166                 type = NL80211_AUTHTYPE_NETWORK_EAP;
2167         else if (params->auth_alg & AUTH_ALG_FT)
2168                 type = NL80211_AUTHTYPE_FT;
2169         else
2170                 goto nla_put_failure;
2171         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
2172         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
2173
2174         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2175         msg = NULL;
2176         if (ret) {
2177                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
2178                            "(%s)", ret, strerror(-ret));
2179                 count++;
2180                 if (ret == -EALREADY && count == 1 && params->bssid) {
2181                         /*
2182                          * mac80211 does not currently accept new
2183                          * authentication if we are already authenticated. As a
2184                          * workaround, force deauthentication and try again.
2185                          */
2186                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
2187                                    "after forced deauthentication");
2188                         wpa_driver_nl80211_deauthenticate(
2189                                 drv, params->bssid,
2190                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
2191                         nlmsg_free(msg);
2192                         goto retry;
2193                 }
2194                 goto nla_put_failure;
2195         }
2196         ret = 0;
2197         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
2198                    "successfully");
2199
2200 nla_put_failure:
2201         nlmsg_free(msg);
2202         return ret;
2203 }
2204
2205
2206 #if defined(CONFIG_AP) || defined(HOSTAPD)
2207
2208 struct phy_info_arg {
2209         u16 *num_modes;
2210         struct hostapd_hw_modes *modes;
2211 };
2212
2213 static int phy_info_handler(struct nl_msg *msg, void *arg)
2214 {
2215         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
2216         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2217         struct phy_info_arg *phy_info = arg;
2218
2219         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
2220
2221         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
2222         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
2223                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
2224                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
2225                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
2226                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
2227                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
2228                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
2229         };
2230
2231         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
2232         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
2233                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
2234                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
2235         };
2236
2237         struct nlattr *nl_band;
2238         struct nlattr *nl_freq;
2239         struct nlattr *nl_rate;
2240         int rem_band, rem_freq, rem_rate;
2241         struct hostapd_hw_modes *mode;
2242         int idx, mode_is_set;
2243
2244         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2245                   genlmsg_attrlen(gnlh, 0), NULL);
2246
2247         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
2248                 return NL_SKIP;
2249
2250         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
2251                 mode = realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
2252                 if (!mode)
2253                         return NL_SKIP;
2254                 phy_info->modes = mode;
2255
2256                 mode_is_set = 0;
2257
2258                 mode = &phy_info->modes[*(phy_info->num_modes)];
2259                 memset(mode, 0, sizeof(*mode));
2260                 *(phy_info->num_modes) += 1;
2261
2262                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
2263                           nla_len(nl_band), NULL);
2264
2265                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
2266                         mode->ht_capab = nla_get_u16(
2267                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
2268                 }
2269
2270                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
2271                         mode->a_mpdu_params |= nla_get_u8(
2272                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
2273                                 0x03;
2274                 }
2275
2276                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
2277                         mode->a_mpdu_params |= nla_get_u8(
2278                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
2279                                 2;
2280                 }
2281
2282                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
2283                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
2284                         u8 *mcs;
2285                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
2286                         os_memcpy(mode->mcs_set, mcs, 16);
2287                 }
2288
2289                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
2290                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
2291                                   nla_len(nl_freq), freq_policy);
2292                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
2293                                 continue;
2294                         mode->num_channels++;
2295                 }
2296
2297                 mode->channels = calloc(mode->num_channels, sizeof(struct hostapd_channel_data));
2298                 if (!mode->channels)
2299                         return NL_SKIP;
2300
2301                 idx = 0;
2302
2303                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
2304                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
2305                                   nla_len(nl_freq), freq_policy);
2306                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
2307                                 continue;
2308
2309                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
2310                         mode->channels[idx].flag = 0;
2311
2312                         if (!mode_is_set) {
2313                                 /* crude heuristic */
2314                                 if (mode->channels[idx].freq < 4000)
2315                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
2316                                 else
2317                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
2318                                 mode_is_set = 1;
2319                         }
2320
2321                         /* crude heuristic */
2322                         if (mode->channels[idx].freq < 4000)
2323                                 if (mode->channels[idx].freq == 2484)
2324                                         mode->channels[idx].chan = 14;
2325                                 else
2326                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
2327                         else
2328                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
2329
2330                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
2331                                 mode->channels[idx].flag |=
2332                                         HOSTAPD_CHAN_DISABLED;
2333                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
2334                                 mode->channels[idx].flag |=
2335                                         HOSTAPD_CHAN_PASSIVE_SCAN;
2336                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
2337                                 mode->channels[idx].flag |=
2338                                         HOSTAPD_CHAN_NO_IBSS;
2339                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
2340                                 mode->channels[idx].flag |=
2341                                         HOSTAPD_CHAN_RADAR;
2342
2343                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
2344                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
2345                                 mode->channels[idx].max_tx_power =
2346                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
2347
2348                         idx++;
2349                 }
2350
2351                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
2352                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
2353                                   nla_len(nl_rate), rate_policy);
2354                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
2355                                 continue;
2356                         mode->num_rates++;
2357                 }
2358
2359                 mode->rates = calloc(mode->num_rates, sizeof(struct hostapd_rate_data));
2360                 if (!mode->rates)
2361                         return NL_SKIP;
2362
2363                 idx = 0;
2364
2365                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
2366                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
2367                                   nla_len(nl_rate), rate_policy);
2368                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
2369                                 continue;
2370                         mode->rates[idx].rate = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
2371
2372                         /* crude heuristic */
2373                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
2374                             mode->rates[idx].rate > 200)
2375                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
2376
2377                         if (tb_rate[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE])
2378                                 mode->rates[idx].flags |= HOSTAPD_RATE_PREAMBLE2;
2379
2380                         idx++;
2381                 }
2382         }
2383
2384         return NL_SKIP;
2385 }
2386
2387 static struct hostapd_hw_modes *
2388 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
2389 {
2390         u16 m;
2391         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
2392         int i, mode11g_idx = -1;
2393
2394         /* If only 802.11g mode is included, use it to construct matching
2395          * 802.11b mode data. */
2396
2397         for (m = 0; m < *num_modes; m++) {
2398                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
2399                         return modes; /* 802.11b already included */
2400                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
2401                         mode11g_idx = m;
2402         }
2403
2404         if (mode11g_idx < 0)
2405                 return modes; /* 2.4 GHz band not supported at all */
2406
2407         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
2408         if (nmodes == NULL)
2409                 return modes; /* Could not add 802.11b mode */
2410
2411         mode = &nmodes[*num_modes];
2412         os_memset(mode, 0, sizeof(*mode));
2413         (*num_modes)++;
2414         modes = nmodes;
2415
2416         mode->mode = HOSTAPD_MODE_IEEE80211B;
2417
2418         mode11g = &modes[mode11g_idx];
2419         mode->num_channels = mode11g->num_channels;
2420         mode->channels = os_malloc(mode11g->num_channels *
2421                                    sizeof(struct hostapd_channel_data));
2422         if (mode->channels == NULL) {
2423                 (*num_modes)--;
2424                 return modes; /* Could not add 802.11b mode */
2425         }
2426         os_memcpy(mode->channels, mode11g->channels,
2427                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
2428
2429         mode->num_rates = 0;
2430         mode->rates = os_malloc(4 * sizeof(struct hostapd_rate_data));
2431         if (mode->rates == NULL) {
2432                 os_free(mode->channels);
2433                 (*num_modes)--;
2434                 return modes; /* Could not add 802.11b mode */
2435         }
2436
2437         for (i = 0; i < mode11g->num_rates; i++) {
2438                 if (mode11g->rates[i].rate > 110 ||
2439                     mode11g->rates[i].flags &
2440                     (HOSTAPD_RATE_ERP | HOSTAPD_RATE_OFDM))
2441                         continue;
2442                 mode->rates[mode->num_rates] = mode11g->rates[i];
2443                 mode->num_rates++;
2444                 if (mode->num_rates == 4)
2445                         break;
2446         }
2447
2448         if (mode->num_rates == 0) {
2449                 os_free(mode->channels);
2450                 os_free(mode->rates);
2451                 (*num_modes)--;
2452                 return modes; /* No 802.11b rates */
2453         }
2454
2455         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
2456                    "information");
2457
2458         return modes;
2459 }
2460
2461
2462 static struct hostapd_hw_modes *
2463 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
2464 {
2465         struct wpa_driver_nl80211_data *drv = priv;
2466         struct nl_msg *msg;
2467         struct phy_info_arg result = {
2468                 .num_modes = num_modes,
2469                 .modes = NULL,
2470         };
2471
2472         *num_modes = 0;
2473         *flags = 0;
2474
2475         msg = nlmsg_alloc();
2476         if (!msg)
2477                 return NULL;
2478
2479         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2480                     0, NL80211_CMD_GET_WIPHY, 0);
2481
2482         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2483
2484         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0)
2485                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
2486  nla_put_failure:
2487         return NULL;
2488 }
2489
2490
2491 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
2492                                          const void *data, size_t len,
2493                                          int encrypt)
2494 {
2495         __u8 rtap_hdr[] = {
2496                 0x00, 0x00, /* radiotap version */
2497                 0x0e, 0x00, /* radiotap length */
2498                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
2499                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
2500                 0x00,       /* padding */
2501                 0x00, 0x00, /* RX and TX flags to indicate that */
2502                 0x00, 0x00, /* this is the injected frame directly */
2503         };
2504         struct iovec iov[2] = {
2505                 {
2506                         .iov_base = &rtap_hdr,
2507                         .iov_len = sizeof(rtap_hdr),
2508                 },
2509                 {
2510                         .iov_base = (void *) data,
2511                         .iov_len = len,
2512                 }
2513         };
2514         struct msghdr msg = {
2515                 .msg_name = NULL,
2516                 .msg_namelen = 0,
2517                 .msg_iov = iov,
2518                 .msg_iovlen = 2,
2519                 .msg_control = NULL,
2520                 .msg_controllen = 0,
2521                 .msg_flags = 0,
2522         };
2523
2524         if (encrypt)
2525                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
2526
2527         return sendmsg(drv->monitor_sock, &msg, 0);
2528 }
2529
2530
2531 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
2532                                         size_t data_len)
2533 {
2534         struct wpa_driver_nl80211_data *drv = priv;
2535         struct ieee80211_mgmt *mgmt;
2536         int encrypt = 1;
2537         u16 fc;
2538
2539         mgmt = (struct ieee80211_mgmt *) data;
2540         fc = le_to_host16(mgmt->frame_control);
2541
2542         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
2543             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
2544                 /*
2545                  * Only one of the authentication frame types is encrypted.
2546                  * In order for static WEP encryption to work properly (i.e.,
2547                  * to not encrypt the frame), we need to tell mac80211 about
2548                  * the frames that must not be encrypted.
2549                  */
2550                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
2551                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
2552                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
2553                         encrypt = 0;
2554         }
2555
2556         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
2557 }
2558
2559 #endif /* CONFIG_AP || HOSTAPD */
2560
2561
2562 static int wpa_driver_nl80211_set_beacon(const char *ifname, void *priv,
2563                                          const u8 *head, size_t head_len,
2564                                          const u8 *tail, size_t tail_len,
2565                                          int dtim_period, int beacon_int)
2566 {
2567         struct wpa_driver_nl80211_data *drv = priv;
2568         struct nl_msg *msg;
2569         u8 cmd = NL80211_CMD_NEW_BEACON;
2570         int ret;
2571         int beacon_set;
2572         int ifindex = if_nametoindex(ifname);
2573 #ifdef HOSTAPD
2574         struct i802_bss *bss;
2575
2576         bss = get_bss(drv, ifindex);
2577         if (bss == NULL)
2578                 return -ENOENT;
2579         beacon_set = bss->beacon_set;
2580 #else /* HOSTAPD */
2581         beacon_set = drv->beacon_set;
2582 #endif /* HOSTAPD */
2583
2584         msg = nlmsg_alloc();
2585         if (!msg)
2586                 return -ENOMEM;
2587
2588         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
2589                    beacon_set);
2590         if (beacon_set)
2591                 cmd = NL80211_CMD_SET_BEACON;
2592
2593         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2594                     0, cmd, 0);
2595         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
2596         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
2597         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2598         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, beacon_int);
2599         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
2600
2601         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2602         if (ret) {
2603                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
2604                            ret, strerror(-ret));
2605         } else {
2606 #ifdef HOSTAPD
2607                 bss->beacon_set = 1;
2608 #else /* HOSTAPD */
2609                 drv->beacon_set = 1;
2610 #endif /* HOSTAPD */
2611         }
2612         return ret;
2613  nla_put_failure:
2614         return -ENOBUFS;
2615 }
2616
2617
2618 #if defined(CONFIG_AP) || defined(HOSTAPD)
2619
2620 static int wpa_driver_nl80211_set_freq(struct wpa_driver_nl80211_data *drv,
2621                                        int freq, int ht_enabled,
2622                                        int sec_channel_offset)
2623 {
2624         struct nl_msg *msg;
2625         int ret;
2626
2627         msg = nlmsg_alloc();
2628         if (!msg)
2629                 return -1;
2630
2631         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2632                     NL80211_CMD_SET_WIPHY, 0);
2633
2634         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2635         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
2636         if (ht_enabled) {
2637                 switch (sec_channel_offset) {
2638                 case -1:
2639                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
2640                                     NL80211_CHAN_HT40MINUS);
2641                         break;
2642                 case 1:
2643                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
2644                                     NL80211_CHAN_HT40PLUS);
2645                         break;
2646                 default:
2647                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
2648                                     NL80211_CHAN_HT20);
2649                         break;
2650                 }
2651         }
2652
2653         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2654         if (ret == 0)
2655                 return 0;
2656         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
2657                    "%d (%s)", freq, ret, strerror(-ret));
2658 nla_put_failure:
2659         return -1;
2660 }
2661
2662
2663 static int wpa_driver_nl80211_sta_add(const char *ifname, void *priv,
2664                                       struct hostapd_sta_add_params *params)
2665 {
2666         struct wpa_driver_nl80211_data *drv = priv;
2667         struct nl_msg *msg;
2668         int ret = -ENOBUFS;
2669
2670         msg = nlmsg_alloc();
2671         if (!msg)
2672                 return -ENOMEM;
2673
2674         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2675                     0, NL80211_CMD_NEW_STATION, 0);
2676
2677         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(ifname));
2678         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
2679         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
2680         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
2681                 params->supp_rates);
2682         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
2683                     params->listen_interval);
2684         if (params->ht_capabilities) {
2685                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
2686                         sizeof(*params->ht_capabilities),
2687                         params->ht_capabilities);
2688         }
2689
2690         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2691         if (ret)
2692                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
2693                            "result: %d (%s)", ret, strerror(-ret));
2694         if (ret == -EEXIST)
2695                 ret = 0;
2696  nla_put_failure:
2697         return ret;
2698 }
2699
2700
2701 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
2702 {
2703         struct wpa_driver_nl80211_data *drv = priv;
2704         struct nl_msg *msg;
2705         int ret;
2706
2707         msg = nlmsg_alloc();
2708         if (!msg)
2709                 return -ENOMEM;
2710
2711         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2712                     0, NL80211_CMD_DEL_STATION, 0);
2713
2714         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
2715                     if_nametoindex(drv->ifname));
2716         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2717
2718         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2719         if (ret == -ENOENT)
2720                 return 0;
2721         return ret;
2722  nla_put_failure:
2723         return -ENOBUFS;
2724 }
2725
2726
2727 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
2728                                  int ifidx)
2729 {
2730         struct nl_msg *msg;
2731
2732 #ifdef HOSTAPD
2733         /* stop listening for EAPOL on this interface */
2734         del_ifidx(drv, ifidx);
2735 #endif /* HOSTAPD */
2736
2737         msg = nlmsg_alloc();
2738         if (!msg)
2739                 goto nla_put_failure;
2740
2741         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2742                     0, NL80211_CMD_DEL_INTERFACE, 0);
2743         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
2744
2745         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
2746                 return;
2747  nla_put_failure:
2748         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d).\n",
2749                    ifidx);
2750 }
2751
2752
2753 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
2754                                      const char *ifname,
2755                                      enum nl80211_iftype iftype,
2756                                      const u8 *addr)
2757 {
2758         struct nl_msg *msg, *flags = NULL;
2759         int ifidx;
2760         int ret = -ENOBUFS;
2761
2762         msg = nlmsg_alloc();
2763         if (!msg)
2764                 return -1;
2765
2766         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2767                     0, NL80211_CMD_NEW_INTERFACE, 0);
2768         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2769         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
2770         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
2771
2772         if (iftype == NL80211_IFTYPE_MONITOR) {
2773                 int err;
2774
2775                 flags = nlmsg_alloc();
2776                 if (!flags)
2777                         goto nla_put_failure;
2778
2779                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
2780
2781                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
2782
2783                 nlmsg_free(flags);
2784
2785                 if (err)
2786                         goto nla_put_failure;
2787         }
2788
2789         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2790         if (ret) {
2791  nla_put_failure:
2792                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
2793                            ifname, ret, strerror(-ret));
2794                 return ret;
2795         }
2796
2797         ifidx = if_nametoindex(ifname);
2798
2799         if (ifidx <= 0)
2800                 return -1;
2801
2802 #ifdef HOSTAPD
2803         /* start listening for EAPOL on this interface */
2804         add_ifidx(drv, ifidx);
2805
2806         if (addr && iftype == NL80211_IFTYPE_AP &&
2807             set_ifhwaddr(drv, ifname, addr)) {
2808                 nl80211_remove_iface(drv, ifidx);
2809                 return -1;
2810         }
2811 #endif /* HOSTAPD */
2812
2813         return ifidx;
2814 }
2815 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
2816                                 const char *ifname, enum nl80211_iftype iftype,
2817                                 const u8 *addr)
2818 {
2819         int ret;
2820
2821         ret = nl80211_create_iface_once(drv, ifname, iftype, addr);
2822
2823         /* if error occured and interface exists already */
2824         if (ret == -ENFILE && if_nametoindex(ifname)) {
2825                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
2826
2827                 /* Try to remove the interface that was already there. */
2828                 nl80211_remove_iface(drv, if_nametoindex(ifname));
2829
2830                 /* Try to create the interface again */
2831                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr);
2832         }
2833
2834         return ret;
2835 }
2836
2837 #endif /* CONFIG_AP || HOSTAPD */
2838
2839 #ifdef CONFIG_AP
2840
2841 void ap_tx_status(void *ctx, const u8 *addr,
2842                   const u8 *buf, size_t len, int ack);
2843 void ap_rx_from_unknown_sta(void *ctx, struct ieee80211_hdr *hdr, size_t len);
2844 void ap_mgmt_rx(void *ctx, u8 *buf, size_t len, u16 stype,
2845                 struct hostapd_frame_info *fi);
2846 void ap_mgmt_tx_cb(void *ctx, u8 *buf, size_t len, u16 stype, int ok);
2847
2848 #endif /* CONFIG_AP */
2849
2850 #if defined(CONFIG_AP) || defined(HOSTAPD)
2851
2852 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
2853 {
2854         struct ieee80211_hdr *hdr;
2855         u16 fc, type, stype;
2856
2857         hdr = (struct ieee80211_hdr *) buf;
2858         fc = le_to_host16(hdr->frame_control);
2859
2860         type = WLAN_FC_GET_TYPE(fc);
2861         stype = WLAN_FC_GET_STYPE(fc);
2862
2863         switch (type) {
2864         case WLAN_FC_TYPE_MGMT:
2865                 wpa_printf(MSG_DEBUG, "MGMT (TX callback) %s",
2866                            ok ? "ACK" : "fail");
2867 #ifdef HOSTAPD
2868                 hostapd_mgmt_tx_cb(ctx, buf, len, stype, ok);
2869 #else /* HOSTAPD */
2870                 ap_mgmt_tx_cb(ctx, buf, len, stype, ok);
2871 #endif /* HOSTAPD */
2872                 break;
2873         case WLAN_FC_TYPE_CTRL:
2874                 wpa_printf(MSG_DEBUG, "CTRL (TX callback) %s",
2875                            ok ? "ACK" : "fail");
2876                 break;
2877         case WLAN_FC_TYPE_DATA:
2878 #ifdef HOSTAPD
2879                 hostapd_tx_status(ctx, hdr->addr1, buf, len, ok);
2880 #else /* HOSTAPD */
2881                 ap_tx_status(ctx, hdr->addr1, buf, len, ok);
2882 #endif /* HOSTAPD */
2883                 break;
2884         default:
2885                 wpa_printf(MSG_DEBUG, "unknown TX callback frame type %d",
2886                            type);
2887                 break;
2888         }
2889 }
2890
2891
2892 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
2893                              struct ieee80211_hdr *hdr, size_t len)
2894 {
2895 #ifdef HOSTAPD
2896         hostapd_rx_from_unknown_sta(drv->ctx, hdr, len);
2897 #else /* HOSTAPD */
2898         ap_rx_from_unknown_sta(drv->ctx, hdr, len);
2899 #endif /* HOSTAPD */
2900 }
2901
2902
2903 static void handle_frame(struct wpa_driver_nl80211_data *drv,
2904                          u8 *buf, size_t len,
2905                          struct hostapd_frame_info *hfi)
2906 {
2907         struct ieee80211_hdr *hdr;
2908         u16 fc, stype;
2909
2910         hdr = (struct ieee80211_hdr *) buf;
2911         fc = le_to_host16(hdr->frame_control);
2912         stype = WLAN_FC_GET_STYPE(fc);
2913
2914         switch (WLAN_FC_GET_TYPE(fc)) {
2915         case WLAN_FC_TYPE_MGMT:
2916                 if (stype != WLAN_FC_STYPE_BEACON &&
2917                     stype != WLAN_FC_STYPE_PROBE_REQ)
2918                         wpa_printf(MSG_MSGDUMP, "MGMT");
2919 #ifdef HOSTAPD
2920                 hostapd_mgmt_rx(drv->ctx, buf, len, stype, hfi);
2921 #else /* HOSTAPD */
2922                 ap_mgmt_rx(drv->ctx, buf, len, stype, hfi);
2923 #endif /* HOSTAPD */
2924                 break;
2925         case WLAN_FC_TYPE_CTRL:
2926                 /* can only get here with PS-Poll frames */
2927                 wpa_printf(MSG_DEBUG, "CTRL");
2928                 from_unknown_sta(drv, hdr, len);
2929                 break;
2930         case WLAN_FC_TYPE_DATA:
2931                 from_unknown_sta(drv, hdr, len);
2932                 break;
2933         }
2934 }
2935
2936
2937 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
2938 {
2939         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2940         int len;
2941         unsigned char buf[3000];
2942         struct ieee80211_radiotap_iterator iter;
2943         int ret;
2944         struct hostapd_frame_info hfi;
2945         int injected = 0, failed = 0, rxflags = 0;
2946
2947         len = recv(sock, buf, sizeof(buf), 0);
2948         if (len < 0) {
2949                 perror("recv");
2950                 return;
2951         }
2952
2953         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
2954                 printf("received invalid radiotap frame\n");
2955                 return;
2956         }
2957
2958         memset(&hfi, 0, sizeof(hfi));
2959
2960         while (1) {
2961                 ret = ieee80211_radiotap_iterator_next(&iter);
2962                 if (ret == -ENOENT)
2963                         break;
2964                 if (ret) {
2965                         printf("received invalid radiotap frame (%d)\n", ret);
2966                         return;
2967                 }
2968                 switch (iter.this_arg_index) {
2969                 case IEEE80211_RADIOTAP_FLAGS:
2970                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
2971                                 len -= 4;
2972                         break;
2973                 case IEEE80211_RADIOTAP_RX_FLAGS:
2974                         rxflags = 1;
2975                         break;
2976                 case IEEE80211_RADIOTAP_TX_FLAGS:
2977                         injected = 1;
2978                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
2979                                         IEEE80211_RADIOTAP_F_TX_FAIL;
2980                         break;
2981                 case IEEE80211_RADIOTAP_DATA_RETRIES:
2982                         break;
2983                 case IEEE80211_RADIOTAP_CHANNEL:
2984                         /* TODO convert from freq/flags to channel number
2985                         hfi.channel = XXX;
2986                         hfi.phytype = XXX;
2987                          */
2988                         break;
2989                 case IEEE80211_RADIOTAP_RATE:
2990                         hfi.datarate = *iter.this_arg * 5;
2991                         break;
2992                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
2993                         hfi.ssi_signal = *iter.this_arg;
2994                         break;
2995                 }
2996         }
2997
2998         if (rxflags && injected)
2999                 return;
3000
3001         if (!injected)
3002                 handle_frame(drv, buf + iter.max_length,
3003                              len - iter.max_length, &hfi);
3004         else
3005                 handle_tx_callback(drv->ctx, buf + iter.max_length,
3006                                    len - iter.max_length, !failed);
3007 }
3008
3009
3010 /*
3011  * we post-process the filter code later and rewrite
3012  * this to the offset to the last instruction
3013  */
3014 #define PASS    0xFF
3015 #define FAIL    0xFE
3016
3017 static struct sock_filter msock_filter_insns[] = {
3018         /*
3019          * do a little-endian load of the radiotap length field
3020          */
3021         /* load lower byte into A */
3022         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
3023         /* put it into X (== index register) */
3024         BPF_STMT(BPF_MISC| BPF_TAX, 0),
3025         /* load upper byte into A */
3026         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
3027         /* left-shift it by 8 */
3028         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
3029         /* or with X */
3030         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
3031         /* put result into X */
3032         BPF_STMT(BPF_MISC| BPF_TAX, 0),
3033
3034         /*
3035          * Allow management frames through, this also gives us those
3036          * management frames that we sent ourselves with status
3037          */
3038         /* load the lower byte of the IEEE 802.11 frame control field */
3039         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
3040         /* mask off frame type and version */
3041         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
3042         /* accept frame if it's both 0, fall through otherwise */
3043         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
3044
3045         /*
3046          * TODO: add a bit to radiotap RX flags that indicates
3047          * that the sending station is not associated, then
3048          * add a filter here that filters on our DA and that flag
3049          * to allow us to deauth frames to that bad station.
3050          *
3051          * Not a regression -- we didn't do it before either.
3052          */
3053
3054 #if 0
3055         /*
3056          * drop non-data frames, WDS frames
3057          */
3058         /* load the lower byte of the frame control field */
3059         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
3060         /* mask off QoS bit */
3061         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
3062         /* drop non-data frames */
3063         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
3064         /* load the upper byte of the frame control field */
3065         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
3066         /* mask off toDS/fromDS */
3067         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
3068         /* drop WDS frames */
3069         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, FAIL, 0),
3070 #endif
3071
3072         /*
3073          * add header length to index
3074          */
3075         /* load the lower byte of the frame control field */
3076         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
3077         /* mask off QoS bit */
3078         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
3079         /* right shift it by 6 to give 0 or 2 */
3080         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
3081         /* add data frame header length */
3082         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
3083         /* add index, was start of 802.11 header */
3084         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
3085         /* move to index, now start of LL header */
3086         BPF_STMT(BPF_MISC | BPF_TAX, 0),
3087
3088         /*
3089          * Accept empty data frames, we use those for
3090          * polling activity.
3091          */
3092         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
3093         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
3094
3095         /*
3096          * Accept EAPOL frames
3097          */
3098         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
3099         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
3100         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
3101         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
3102
3103         /* keep these last two statements or change the code below */
3104         /* return 0 == "DROP" */
3105         BPF_STMT(BPF_RET | BPF_K, 0),
3106         /* return ~0 == "keep all" */
3107         BPF_STMT(BPF_RET | BPF_K, ~0),
3108 };
3109
3110 static struct sock_fprog msock_filter = {
3111         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
3112         .filter = msock_filter_insns,
3113 };
3114
3115
3116 static int add_monitor_filter(int s)
3117 {
3118         int idx;
3119
3120         /* rewrite all PASS/FAIL jump offsets */
3121         for (idx = 0; idx < msock_filter.len; idx++) {
3122                 struct sock_filter *insn = &msock_filter_insns[idx];
3123
3124                 if (BPF_CLASS(insn->code) == BPF_JMP) {
3125                         if (insn->code == (BPF_JMP|BPF_JA)) {
3126                                 if (insn->k == PASS)
3127                                         insn->k = msock_filter.len - idx - 2;
3128                                 else if (insn->k == FAIL)
3129                                         insn->k = msock_filter.len - idx - 3;
3130                         }
3131
3132                         if (insn->jt == PASS)
3133                                 insn->jt = msock_filter.len - idx - 2;
3134                         else if (insn->jt == FAIL)
3135                                 insn->jt = msock_filter.len - idx - 3;
3136
3137                         if (insn->jf == PASS)
3138                                 insn->jf = msock_filter.len - idx - 2;
3139                         else if (insn->jf == FAIL)
3140                                 insn->jf = msock_filter.len - idx - 3;
3141                 }
3142         }
3143
3144         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
3145                        &msock_filter, sizeof(msock_filter))) {
3146                 perror("SO_ATTACH_FILTER");
3147                 return -1;
3148         }
3149
3150         return 0;
3151 }
3152
3153
3154 static void nl80211_remove_monitor_interface(
3155         struct wpa_driver_nl80211_data *drv)
3156 {
3157         if (drv->monitor_ifidx >= 0) {
3158                 nl80211_remove_iface(drv, drv->monitor_ifidx);
3159                 drv->monitor_ifidx = -1;
3160         }
3161 }
3162
3163
3164 static int
3165 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
3166 {
3167         char buf[IFNAMSIZ];
3168         struct sockaddr_ll ll;
3169         int optval;
3170         socklen_t optlen;
3171
3172         snprintf(buf, IFNAMSIZ, "mon.%s", drv->ifname);
3173         buf[IFNAMSIZ - 1] = '\0';
3174
3175         drv->monitor_ifidx =
3176                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL);
3177
3178         if (drv->monitor_ifidx < 0)
3179                 return -1;
3180
3181         if (hostapd_set_iface_flags(drv, buf, 1))
3182                 goto error;
3183
3184         memset(&ll, 0, sizeof(ll));
3185         ll.sll_family = AF_PACKET;
3186         ll.sll_ifindex = drv->monitor_ifidx;
3187         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
3188         if (drv->monitor_sock < 0) {
3189                 perror("socket[PF_PACKET,SOCK_RAW]");
3190                 goto error;
3191         }
3192
3193         if (add_monitor_filter(drv->monitor_sock)) {
3194                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
3195                            "interface; do filtering in user space");
3196                 /* This works, but will cost in performance. */
3197         }
3198
3199         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
3200                 perror("monitor socket bind");
3201                 goto error;
3202         }
3203
3204         optlen = sizeof(optval);
3205         optval = 20;
3206         if (setsockopt
3207             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
3208                 perror("Failed to set socket priority");
3209                 goto error;
3210         }
3211
3212         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
3213                                      drv, NULL)) {
3214                 printf("Could not register monitor read socket\n");
3215                 goto error;
3216         }
3217
3218         return 0;
3219  error:
3220         nl80211_remove_monitor_interface(drv);
3221         return -1;
3222 }
3223
3224
3225 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
3226
3227 static int wpa_driver_nl80211_hapd_send_eapol(
3228         void *priv, const u8 *addr, const u8 *data,
3229         size_t data_len, int encrypt, const u8 *own_addr)
3230 {
3231         struct wpa_driver_nl80211_data *drv = priv;
3232         struct ieee80211_hdr *hdr;
3233         size_t len;
3234         u8 *pos;
3235         int res;
3236 #if 0 /* FIX */
3237         int qos = sta->flags & WLAN_STA_WME;
3238 #else
3239         int qos = 0;
3240 #endif
3241
3242         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
3243                 data_len;
3244         hdr = os_zalloc(len);
3245         if (hdr == NULL) {
3246                 printf("malloc() failed for i802_send_data(len=%lu)\n",
3247                        (unsigned long) len);
3248                 return -1;
3249         }
3250
3251         hdr->frame_control =
3252                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
3253         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
3254         if (encrypt)
3255                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
3256 #if 0 /* To be enabled if qos determination is added above */
3257         if (qos) {
3258                 hdr->frame_control |=
3259                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
3260         }
3261 #endif
3262
3263         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
3264         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
3265         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
3266         pos = (u8 *) (hdr + 1);
3267
3268 #if 0 /* To be enabled if qos determination is added above */
3269         if (qos) {
3270                 /* add an empty QoS header if needed */
3271                 pos[0] = 0;
3272                 pos[1] = 0;
3273                 pos += 2;
3274         }
3275 #endif
3276
3277         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
3278         pos += sizeof(rfc1042_header);
3279         WPA_PUT_BE16(pos, ETH_P_PAE);
3280         pos += 2;
3281         memcpy(pos, data, data_len);
3282
3283         res = wpa_driver_nl80211_send_frame(drv, (u8 *) hdr, len, encrypt);
3284         if (res < 0) {
3285                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
3286                            "failed: %d (%s)",
3287                            (unsigned long) len, errno, strerror(errno));
3288         }
3289         free(hdr);
3290
3291         return res;
3292 }
3293
3294
3295 static u32 sta_flags_nl80211(int flags)
3296 {
3297         u32 f = 0;
3298
3299         if (flags & WLAN_STA_AUTHORIZED)
3300                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
3301         if (flags & WLAN_STA_WMM)
3302                 f |= BIT(NL80211_STA_FLAG_WME);
3303         if (flags & WLAN_STA_SHORT_PREAMBLE)
3304                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
3305         if (flags & WLAN_STA_MFP)
3306                 f |= BIT(NL80211_STA_FLAG_MFP);
3307
3308         return f;
3309 }
3310
3311
3312 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
3313                                             int total_flags, int flags_or,
3314                                             int flags_and)
3315 {
3316         struct wpa_driver_nl80211_data *drv = priv;
3317         struct nl_msg *msg, *flags = NULL;
3318         struct nl80211_sta_flag_update upd;
3319
3320         msg = nlmsg_alloc();
3321         if (!msg)
3322                 return -ENOMEM;
3323
3324         flags = nlmsg_alloc();
3325         if (!flags) {
3326                 nlmsg_free(msg);
3327                 return -ENOMEM;
3328         }
3329
3330         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3331                     0, NL80211_CMD_SET_STATION, 0);
3332
3333         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3334                     if_nametoindex(drv->ifname));
3335         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3336
3337         /*
3338          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
3339          * can be removed eventually.
3340          */
3341         if (total_flags & WLAN_STA_AUTHORIZED)
3342                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
3343
3344         if (total_flags & WLAN_STA_WMM)
3345                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
3346
3347         if (total_flags & WLAN_STA_SHORT_PREAMBLE)
3348                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
3349
3350         if (total_flags & WLAN_STA_MFP)
3351                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
3352
3353         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
3354                 goto nla_put_failure;
3355
3356         os_memset(&upd, 0, sizeof(upd));
3357         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
3358         upd.set = sta_flags_nl80211(flags_or);
3359         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
3360
3361         nlmsg_free(flags);
3362
3363         return send_and_recv_msgs(drv, msg, NULL, NULL);
3364  nla_put_failure:
3365         nlmsg_free(flags);
3366         return -ENOBUFS;
3367 }
3368
3369 #endif /* CONFIG_AP || HOSTAPD */
3370
3371 #ifdef CONFIG_AP
3372
3373 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
3374                                  struct wpa_driver_associate_params *params)
3375 {
3376         if (wpa_driver_nl80211_set_mode(drv, params->mode) ||
3377             wpa_driver_nl80211_set_freq(drv, params->freq, 0, 0)) {
3378                 nl80211_remove_monitor_interface(drv);
3379                 return -1;
3380         }
3381
3382         /* TODO: setup monitor interface (and add code somewhere to remove this
3383          * when AP mode is stopped; associate with mode != 2 or drv_deinit) */
3384
3385         return 0;
3386 }
3387 #endif /* CONFIG_AP */
3388
3389
3390 static int wpa_driver_nl80211_connect(
3391         struct wpa_driver_nl80211_data *drv,
3392         struct wpa_driver_associate_params *params)
3393 {
3394         struct nl_msg *msg;
3395         enum nl80211_auth_type type;
3396         int ret = 0;
3397
3398         msg = nlmsg_alloc();
3399         if (!msg)
3400                 return -1;
3401
3402         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
3403         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3404                     NL80211_CMD_CONNECT, 0);
3405
3406         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3407         if (params->bssid) {
3408                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
3409                            MAC2STR(params->bssid));
3410                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
3411         }
3412         if (params->freq) {
3413                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
3414                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
3415         }
3416         if (params->ssid) {
3417                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
3418                                   params->ssid, params->ssid_len);
3419                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
3420                         params->ssid);
3421                 if (params->ssid_len > sizeof(drv->ssid))
3422                         goto nla_put_failure;
3423                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
3424                 drv->ssid_len = params->ssid_len;
3425         }
3426         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
3427         if (params->wpa_ie)
3428                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
3429                         params->wpa_ie);
3430
3431         if (params->auth_alg & AUTH_ALG_OPEN_SYSTEM)
3432                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
3433         else if (params->auth_alg & AUTH_ALG_SHARED_KEY)
3434                 type = NL80211_AUTHTYPE_SHARED_KEY;
3435         else if (params->auth_alg & AUTH_ALG_LEAP)
3436                 type = NL80211_AUTHTYPE_NETWORK_EAP;
3437         else if (params->auth_alg & AUTH_ALG_FT)
3438                 type = NL80211_AUTHTYPE_FT;
3439         else
3440                 goto nla_put_failure;
3441
3442         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
3443         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
3444
3445         if (params->wpa_ie && params->wpa_ie_len) {
3446                 enum nl80211_wpa_versions ver;
3447
3448                 if (params->wpa_ie[0] == WLAN_EID_RSN)
3449                         ver = NL80211_WPA_VERSION_2;
3450                 else
3451                         ver = NL80211_WPA_VERSION_1;
3452
3453                 wpa_printf(MSG_DEBUG, "  * WPA Version %d", ver);
3454                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
3455         }
3456
3457         if (params->pairwise_suite != CIPHER_NONE) {
3458                 int cipher;
3459
3460                 switch (params->pairwise_suite) {
3461                 case CIPHER_WEP40:
3462                         cipher = WLAN_CIPHER_SUITE_WEP40;
3463                         break;
3464                 case CIPHER_WEP104:
3465                         cipher = WLAN_CIPHER_SUITE_WEP104;
3466                         break;
3467                 case CIPHER_CCMP:
3468                         cipher = WLAN_CIPHER_SUITE_CCMP;
3469                         break;
3470                 case CIPHER_TKIP:
3471                 default:
3472                         cipher = WLAN_CIPHER_SUITE_TKIP;
3473                         break;
3474                 }
3475                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
3476         }
3477
3478         if (params->group_suite != CIPHER_NONE) {
3479                 int cipher;
3480
3481                 switch (params->group_suite) {
3482                 case CIPHER_WEP40:
3483                         cipher = WLAN_CIPHER_SUITE_WEP40;
3484                         break;
3485                 case CIPHER_WEP104:
3486                         cipher = WLAN_CIPHER_SUITE_WEP104;
3487                         break;
3488                 case CIPHER_CCMP:
3489                         cipher = WLAN_CIPHER_SUITE_CCMP;
3490                         break;
3491                 case CIPHER_TKIP:
3492                 default:
3493                         cipher = WLAN_CIPHER_SUITE_TKIP;
3494                         break;
3495                 }
3496                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
3497         }
3498
3499         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
3500             params->key_mgmt_suite == KEY_MGMT_PSK) {
3501                 int mgmt = WLAN_AKM_SUITE_PSK;
3502
3503                 switch (params->key_mgmt_suite) {
3504                 case KEY_MGMT_802_1X:
3505                         mgmt = WLAN_AKM_SUITE_8021X;
3506                         break;
3507                 case KEY_MGMT_PSK:
3508                 default:
3509                         mgmt = WLAN_AKM_SUITE_PSK;
3510                         break;
3511                 }
3512                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
3513         }
3514
3515         ret = nl80211_set_conn_keys(params, msg);
3516         if (ret)
3517                 goto nla_put_failure;
3518
3519         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3520         msg = NULL;
3521         if (ret) {
3522                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
3523                            "(%s)", ret, strerror(-ret));
3524                 goto nla_put_failure;
3525         }
3526         ret = 0;
3527         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
3528
3529 nla_put_failure:
3530         nlmsg_free(msg);
3531         return ret;
3532
3533 }
3534
3535
3536 static int wpa_driver_nl80211_associate(
3537         void *priv, struct wpa_driver_associate_params *params)
3538 {
3539         struct wpa_driver_nl80211_data *drv = priv;
3540         int ret = -1;
3541         struct nl_msg *msg;
3542
3543 #ifdef CONFIG_AP
3544         if (params->mode == 2)
3545                 return wpa_driver_nl80211_ap(drv, params);
3546 #endif /* CONFIG_AP */
3547
3548         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
3549                 if (wpa_driver_nl80211_set_mode(drv, params->mode) < 0)
3550                         return -1;
3551                 return wpa_driver_nl80211_connect(drv, params);
3552         }
3553
3554         drv->associated = 0;
3555
3556         msg = nlmsg_alloc();
3557         if (!msg)
3558                 return -1;
3559
3560         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
3561                    drv->ifindex);
3562         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3563                     NL80211_CMD_ASSOCIATE, 0);
3564
3565         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3566         if (params->bssid) {
3567                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
3568                            MAC2STR(params->bssid));
3569                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
3570         }
3571         if (params->freq) {
3572                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
3573                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
3574         }
3575         if (params->ssid) {
3576                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
3577                                   params->ssid, params->ssid_len);
3578                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
3579                         params->ssid);
3580                 if (params->ssid_len > sizeof(drv->ssid))
3581                         goto nla_put_failure;
3582                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
3583                 drv->ssid_len = params->ssid_len;
3584         }
3585         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
3586         if (params->wpa_ie)
3587                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
3588                         params->wpa_ie);
3589
3590 #ifdef CONFIG_IEEE80211W
3591         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
3592                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
3593 #endif /* CONFIG_IEEE80211W */
3594
3595         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
3596
3597         if (params->prev_bssid) {
3598                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
3599                            MAC2STR(params->prev_bssid));
3600                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
3601                         params->prev_bssid);
3602         }
3603
3604         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3605         msg = NULL;
3606         if (ret) {
3607                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
3608                            "(%s)", ret, strerror(-ret));
3609                 goto nla_put_failure;
3610         }
3611         ret = 0;
3612         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
3613                    "successfully");
3614
3615 nla_put_failure:
3616         nlmsg_free(msg);
3617         return ret;
3618 }
3619
3620
3621 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
3622                             int ifindex, int mode)
3623 {
3624         struct nl_msg *msg;
3625         int ret = -ENOBUFS;
3626
3627         msg = nlmsg_alloc();
3628         if (!msg)
3629                 return -ENOMEM;
3630
3631         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3632                     0, NL80211_CMD_SET_INTERFACE, 0);
3633         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
3634         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
3635
3636         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3637         if (!ret)
3638                 return 0;
3639 nla_put_failure:
3640         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
3641                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
3642         return ret;
3643 }
3644
3645
3646 static int wpa_driver_nl80211_set_mode(void *priv, int mode)
3647 {
3648         struct wpa_driver_nl80211_data *drv = priv;
3649         int ret = -1;
3650         int nlmode;
3651
3652         switch (mode) {
3653         case 0:
3654                 nlmode = NL80211_IFTYPE_STATION;
3655                 break;
3656         case 1:
3657                 nlmode = NL80211_IFTYPE_ADHOC;
3658                 break;
3659         case 2:
3660                 nlmode = NL80211_IFTYPE_AP;
3661                 break;
3662         default:
3663                 return -1;
3664         }
3665
3666         if (nl80211_set_mode(drv, drv->ifindex, nlmode) == 0) {
3667                 drv->nlmode = nlmode;
3668                 ret = 0;
3669                 goto done;
3670         }
3671
3672         if (nlmode == drv->nlmode) {
3673                 ret = 0;
3674                 goto done; /* Already in the requested mode */
3675         }
3676
3677         /* mac80211 doesn't allow mode changes while the device is up, so
3678          * take the device down, try to set the mode again, and bring the
3679          * device back up.
3680          */
3681         if (hostapd_set_iface_flags(drv, drv->ifname, 0) == 0) {
3682                 /* Try to set the mode again while the interface is down */
3683                 ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
3684                 if (hostapd_set_iface_flags(drv, drv->ifname, 1))
3685                         ret = -1;
3686         }
3687
3688         if (!ret)
3689                 drv->nlmode = nlmode;
3690
3691 done:
3692 #if defined(CONFIG_AP) || defined(HOSTAPD)
3693         if (!ret && nlmode == NL80211_IFTYPE_AP) {
3694                 /* Setup additional AP mode functionality if needed */
3695                 if (drv->monitor_ifidx < 0 &&
3696                     nl80211_create_monitor_interface(drv))
3697                         return -1;
3698         } else if (!ret && nlmode != NL80211_IFTYPE_AP) {
3699                 /* Remove additional AP mode functionality */
3700                 nl80211_remove_monitor_interface(drv);
3701         }
3702 #endif /* CONFIG_AP || HOSTAPD */
3703
3704         return ret;
3705 }
3706
3707
3708 static int wpa_driver_nl80211_get_capa(void *priv,
3709                                        struct wpa_driver_capa *capa)
3710 {
3711         struct wpa_driver_nl80211_data *drv = priv;
3712         if (!drv->has_capability)
3713                 return -1;
3714         os_memcpy(capa, &drv->capa, sizeof(*capa));
3715         return 0;
3716 }
3717
3718
3719 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
3720 {
3721         struct wpa_driver_nl80211_data *drv = priv;
3722
3723         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
3724                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
3725         drv->operstate = state;
3726         return wpa_driver_nl80211_send_oper_ifla(
3727                 drv, -1, state ? IF_OPER_UP : IF_OPER_DORMANT);
3728 }
3729
3730
3731 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
3732 {
3733         struct wpa_driver_nl80211_data *drv = priv;
3734         struct nl_msg *msg;
3735         struct nl80211_sta_flag_update upd;
3736
3737         msg = nlmsg_alloc();
3738         if (!msg)
3739                 return -ENOMEM;
3740
3741         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3742                     0, NL80211_CMD_SET_STATION, 0);
3743
3744         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3745                     if_nametoindex(drv->ifname));
3746         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
3747
3748         os_memset(&upd, 0, sizeof(upd));
3749         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
3750         if (authorized)
3751                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
3752         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
3753
3754         return send_and_recv_msgs(drv, msg, NULL, NULL);
3755  nla_put_failure:
3756         return -ENOBUFS;
3757 }
3758
3759
3760 #ifdef HOSTAPD
3761
3762 static struct i802_bss * get_bss(struct wpa_driver_nl80211_data *drv,
3763                                  int ifindex)
3764 {
3765         struct i802_bss *bss = &drv->bss;
3766         while (bss) {
3767                 if (ifindex == bss->ifindex)
3768                         return bss;
3769                 bss = bss->next;
3770         }
3771         wpa_printf(MSG_DEBUG, "nl80211: get_bss(%d) failed", ifindex);
3772         return NULL;
3773 }
3774
3775
3776 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
3777 {
3778         int i;
3779         int *old;
3780
3781         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
3782                    ifidx);
3783         for (i = 0; i < drv->num_if_indices; i++) {
3784                 if (drv->if_indices[i] == 0) {
3785                         drv->if_indices[i] = ifidx;
3786                         return;
3787                 }
3788         }
3789
3790         if (drv->if_indices != drv->default_if_indices)
3791                 old = drv->if_indices;
3792         else
3793                 old = NULL;
3794
3795         drv->if_indices = realloc(old,
3796                                   sizeof(int) * (drv->num_if_indices + 1));
3797         if (!drv->if_indices) {
3798                 if (!old)
3799                         drv->if_indices = drv->default_if_indices;
3800                 else
3801                         drv->if_indices = old;
3802                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
3803                            "interfaces");
3804                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
3805                 return;
3806         }
3807         drv->if_indices[drv->num_if_indices] = ifidx;
3808         drv->num_if_indices++;
3809 }
3810
3811
3812 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
3813 {
3814         int i;
3815
3816         for (i = 0; i < drv->num_if_indices; i++) {
3817                 if (drv->if_indices[i] == ifidx) {
3818                         drv->if_indices[i] = 0;
3819                         break;
3820                 }
3821         }
3822 }
3823
3824
3825 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
3826 {
3827         int i;
3828
3829         for (i = 0; i < drv->num_if_indices; i++)
3830                 if (drv->if_indices[i] == ifidx)
3831                         return 1;
3832
3833         return 0;
3834 }
3835
3836
3837 static inline int min_int(int a, int b)
3838 {
3839         if (a < b)
3840                 return a;
3841         return b;
3842 }
3843
3844
3845 static int get_key_handler(struct nl_msg *msg, void *arg)
3846 {
3847         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3848         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3849
3850         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3851                   genlmsg_attrlen(gnlh, 0), NULL);
3852
3853         /*
3854          * TODO: validate the key index and mac address!
3855          * Otherwise, there's a race condition as soon as
3856          * the kernel starts sending key notifications.
3857          */
3858
3859         if (tb[NL80211_ATTR_KEY_SEQ])
3860                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
3861                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
3862         return NL_SKIP;
3863 }
3864
3865
3866 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
3867                            int idx, u8 *seq)
3868 {
3869         struct wpa_driver_nl80211_data *drv = priv;
3870         struct nl_msg *msg;
3871
3872         msg = nlmsg_alloc();
3873         if (!msg)
3874                 return -ENOMEM;
3875
3876         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3877                     0, NL80211_CMD_GET_KEY, 0);
3878
3879         if (addr)
3880                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3881         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
3882         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
3883
3884         memset(seq, 0, 6);
3885
3886         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
3887  nla_put_failure:
3888         return -ENOBUFS;
3889 }
3890
3891
3892 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
3893                               int mode)
3894 {
3895         struct wpa_driver_nl80211_data *drv = priv;
3896         struct nl_msg *msg;
3897         u8 rates[NL80211_MAX_SUPP_RATES];
3898         u8 rates_len = 0;
3899         int i;
3900
3901         msg = nlmsg_alloc();
3902         if (!msg)
3903                 return -ENOMEM;
3904
3905         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3906                     NL80211_CMD_SET_BSS, 0);
3907
3908         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
3909                 rates[rates_len++] = basic_rates[i] / 5;
3910
3911         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
3912
3913         /* TODO: multi-BSS support */
3914         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3915
3916         return send_and_recv_msgs(drv, msg, NULL, NULL);
3917  nla_put_failure:
3918         return -ENOBUFS;
3919 }
3920
3921
3922 /* Set kernel driver on given frequency (MHz) */
3923 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
3924 {
3925         struct wpa_driver_nl80211_data *drv = priv;
3926         return wpa_driver_nl80211_set_freq(drv, freq->freq, freq->ht_enabled,
3927                                            freq->sec_channel_offset);
3928 }
3929
3930
3931 static int i802_set_rts(void *priv, int rts)
3932 {
3933         struct wpa_driver_nl80211_data *drv = priv;
3934         struct nl_msg *msg;
3935         int ret = -ENOBUFS;
3936         u32 val;
3937
3938         msg = nlmsg_alloc();
3939         if (!msg)
3940                 return -ENOMEM;
3941
3942         if (rts >= 2347)
3943                 val = (u32) -1;
3944         else
3945                 val = rts;
3946
3947         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3948                     0, NL80211_CMD_SET_WIPHY, 0);
3949         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3950         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
3951
3952         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3953         if (!ret)
3954                 return 0;
3955 nla_put_failure:
3956         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
3957                    "%d (%s)", rts, ret, strerror(-ret));
3958         return ret;
3959 }
3960
3961
3962 static int i802_set_frag(void *priv, int frag)
3963 {
3964         struct wpa_driver_nl80211_data *drv = priv;
3965         struct nl_msg *msg;
3966         int ret = -ENOBUFS;
3967         u32 val;
3968
3969         msg = nlmsg_alloc();
3970         if (!msg)
3971                 return -ENOMEM;
3972
3973         if (frag >= 2346)
3974                 val = (u32) -1;
3975         else
3976                 val = frag;
3977
3978         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3979                     0, NL80211_CMD_SET_WIPHY, 0);
3980         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3981         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
3982
3983         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3984         if (!ret)
3985                 return 0;
3986 nla_put_failure:
3987         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
3988                    "%d: %d (%s)", frag, ret, strerror(-ret));
3989         return ret;
3990 }
3991
3992
3993 static int i802_flush(void *priv)
3994 {
3995         struct wpa_driver_nl80211_data *drv = priv;
3996         struct nl_msg *msg;
3997
3998         msg = nlmsg_alloc();
3999         if (!msg)
4000                 return -1;
4001
4002         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4003                     0, NL80211_CMD_DEL_STATION, 0);
4004
4005         /*
4006          * XXX: FIX! this needs to flush all VLANs too
4007          */
4008         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4009                     if_nametoindex(drv->ifname));
4010
4011         return send_and_recv_msgs(drv, msg, NULL, NULL);
4012  nla_put_failure:
4013         return -ENOBUFS;
4014 }
4015
4016
4017 static int get_sta_handler(struct nl_msg *msg, void *arg)
4018 {
4019         struct nlattr *tb[NL80211_ATTR_MAX + 1];
4020         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4021         struct hostap_sta_driver_data *data = arg;
4022         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
4023         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
4024                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
4025                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
4026                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
4027                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
4028                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
4029         };
4030
4031         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4032                   genlmsg_attrlen(gnlh, 0), NULL);
4033
4034         /*
4035          * TODO: validate the interface and mac address!
4036          * Otherwise, there's a race condition as soon as
4037          * the kernel starts sending station notifications.
4038          */
4039
4040         if (!tb[NL80211_ATTR_STA_INFO]) {
4041                 wpa_printf(MSG_DEBUG, "sta stats missing!");
4042                 return NL_SKIP;
4043         }
4044         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
4045                              tb[NL80211_ATTR_STA_INFO],
4046                              stats_policy)) {
4047                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
4048                 return NL_SKIP;
4049         }
4050
4051         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
4052                 data->inactive_msec =
4053                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
4054         if (stats[NL80211_STA_INFO_RX_BYTES])
4055                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
4056         if (stats[NL80211_STA_INFO_TX_BYTES])
4057                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
4058         if (stats[NL80211_STA_INFO_RX_PACKETS])
4059                 data->rx_packets =
4060                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
4061         if (stats[NL80211_STA_INFO_TX_PACKETS])
4062                 data->tx_packets =
4063                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
4064
4065         return NL_SKIP;
4066 }
4067
4068 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
4069                               const u8 *addr)
4070 {
4071         struct wpa_driver_nl80211_data *drv = priv;
4072         struct nl_msg *msg;
4073
4074         os_memset(data, 0, sizeof(*data));
4075         msg = nlmsg_alloc();
4076         if (!msg)
4077                 return -ENOMEM;
4078
4079         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4080                     0, NL80211_CMD_GET_STATION, 0);
4081
4082         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4083         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
4084
4085         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
4086  nla_put_failure:
4087         return -ENOBUFS;
4088 }
4089
4090
4091 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
4092                                     int cw_min, int cw_max, int burst_time)
4093 {
4094         struct wpa_driver_nl80211_data *drv = priv;
4095         struct nl_msg *msg;
4096         struct nlattr *txq, *params;
4097
4098         msg = nlmsg_alloc();
4099         if (!msg)
4100                 return -1;
4101
4102         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4103                     0, NL80211_CMD_SET_WIPHY, 0);
4104
4105         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
4106
4107         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
4108         if (!txq)
4109                 goto nla_put_failure;
4110
4111         /* We are only sending parameters for a single TXQ at a time */
4112         params = nla_nest_start(msg, 1);
4113         if (!params)
4114                 goto nla_put_failure;
4115
4116         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, queue);
4117         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
4118          * 32 usec, so need to convert the value here. */
4119         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
4120         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
4121         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
4122         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
4123
4124         nla_nest_end(msg, params);
4125
4126         nla_nest_end(msg, txq);
4127
4128         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
4129                 return 0;
4130  nla_put_failure:
4131         return -1;
4132 }
4133
4134
4135 static int i802_bss_add(void *priv, const char *ifname, const u8 *bssid)
4136 {
4137         struct wpa_driver_nl80211_data *drv = priv;
4138         int ifidx;
4139         struct i802_bss *bss;
4140
4141         bss = os_zalloc(sizeof(*bss));
4142         if (bss == NULL)
4143                 return -1;
4144
4145         ifidx = nl80211_create_iface(priv, ifname, NL80211_IFTYPE_AP, bssid);
4146         if (ifidx < 0) {
4147                 os_free(bss);
4148                 return -1;
4149         }
4150         bss->ifindex = ifidx;
4151         if (hostapd_set_iface_flags(priv, ifname, 1)) {
4152                 nl80211_remove_iface(priv, ifidx);
4153                 os_free(bss);
4154                 return -1;
4155         }
4156         bss->next = drv->bss.next;
4157         drv->bss.next = bss;
4158         return 0;
4159 }
4160
4161
4162 static int i802_bss_remove(void *priv, const char *ifname)
4163 {
4164         struct wpa_driver_nl80211_data *drv = priv;
4165         struct i802_bss *bss, *prev;
4166         int ifindex = if_nametoindex(ifname);
4167         nl80211_remove_iface(priv, ifindex);
4168         prev = &drv->bss;
4169         bss = drv->bss.next;
4170         while (bss) {
4171                 if (ifindex == bss->ifindex) {
4172                         prev->next = bss->next;
4173                         os_free(bss);
4174                         break;
4175                 }
4176                 prev = bss;
4177                 bss = bss->next;
4178         }
4179         return 0;
4180 }
4181
4182
4183 static int i802_set_bss(void *priv, int cts, int preamble, int slot)
4184 {
4185         struct wpa_driver_nl80211_data *drv = priv;
4186         struct nl_msg *msg;
4187
4188         msg = nlmsg_alloc();
4189         if (!msg)
4190                 return -ENOMEM;
4191
4192         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4193                     NL80211_CMD_SET_BSS, 0);
4194
4195         if (cts >= 0)
4196                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
4197         if (preamble >= 0)
4198                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
4199         if (slot >= 0)
4200                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
4201
4202         /* TODO: multi-BSS support */
4203         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
4204
4205         return send_and_recv_msgs(drv, msg, NULL, NULL);
4206  nla_put_failure:
4207         return -ENOBUFS;
4208 }
4209
4210
4211 static int i802_set_cts_protect(void *priv, int value)
4212 {
4213         return i802_set_bss(priv, value, -1, -1);
4214 }
4215
4216
4217 static int i802_set_preamble(void *priv, int value)
4218 {
4219         return i802_set_bss(priv, -1, value, -1);
4220 }
4221
4222
4223 static int i802_set_short_slot_time(void *priv, int value)
4224 {
4225         return i802_set_bss(priv, -1, -1, value);
4226 }
4227
4228
4229 static enum nl80211_iftype i802_if_type(enum hostapd_driver_if_type type)
4230 {
4231         switch (type) {
4232         case HOSTAPD_IF_VLAN:
4233                 return NL80211_IFTYPE_AP_VLAN;
4234         }
4235         return -1;
4236 }
4237
4238
4239 static int i802_if_add(const char *iface, void *priv,
4240                        enum hostapd_driver_if_type type, char *ifname,
4241                        const u8 *addr)
4242 {
4243         if (nl80211_create_iface(priv, ifname, i802_if_type(type), addr) < 0)
4244                 return -1;
4245         return 0;
4246 }
4247
4248
4249 static int i802_if_update(void *priv, enum hostapd_driver_if_type type,
4250                           char *ifname, const u8 *addr)
4251 {
4252         /* unused at the moment */
4253         return -1;
4254 }
4255
4256
4257 static int i802_if_remove(void *priv, enum hostapd_driver_if_type type,
4258                           const char *ifname, const u8 *addr)
4259 {
4260         nl80211_remove_iface(priv, if_nametoindex(ifname));
4261         return 0;
4262 }
4263
4264
4265 static int i802_set_sta_vlan(void *priv, const u8 *addr,
4266                              const char *ifname, int vlan_id)
4267 {
4268         struct wpa_driver_nl80211_data *drv = priv;
4269         struct nl_msg *msg;
4270
4271         msg = nlmsg_alloc();
4272         if (!msg)
4273                 return -ENOMEM;
4274
4275         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4276                     0, NL80211_CMD_SET_STATION, 0);
4277
4278         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4279                     if_nametoindex(drv->ifname));
4280         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4281         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
4282                     if_nametoindex(ifname));
4283
4284         return send_and_recv_msgs(drv, msg, NULL, NULL);
4285  nla_put_failure:
4286         return -ENOBUFS;
4287 }
4288
4289
4290 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
4291 {
4292         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4293         struct sockaddr_ll lladdr;
4294         unsigned char buf[3000];
4295         int len;
4296         socklen_t fromlen = sizeof(lladdr);
4297
4298         len = recvfrom(sock, buf, sizeof(buf), 0,
4299                        (struct sockaddr *)&lladdr, &fromlen);
4300         if (len < 0) {
4301                 perror("recv");
4302                 return;
4303         }
4304
4305         if (have_ifidx(drv, lladdr.sll_ifindex)) {
4306                 void *ctx;
4307                 ctx = hostapd_sta_get_bss(drv->ctx, lladdr.sll_addr);
4308                 if (!ctx)
4309                         return;
4310                 hostapd_eapol_receive(ctx, lladdr.sll_addr, buf, len);
4311         }
4312 }
4313
4314
4315 static int i802_get_inact_sec(void *priv, const u8 *addr)
4316 {
4317         struct hostap_sta_driver_data data;
4318         int ret;
4319
4320         data.inactive_msec = (unsigned long) -1;
4321         ret = i802_read_sta_data(priv, &data, addr);
4322         if (ret || data.inactive_msec == (unsigned long) -1)
4323                 return -1;
4324         return data.inactive_msec / 1000;
4325 }
4326
4327
4328 static int i802_sta_clear_stats(void *priv, const u8 *addr)
4329 {
4330 #if 0
4331         /* TODO */
4332 #endif
4333         return 0;
4334 }
4335
4336
4337 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
4338                            int reason)
4339 {
4340         struct wpa_driver_nl80211_data *drv = priv;
4341         struct ieee80211_mgmt mgmt;
4342
4343         memset(&mgmt, 0, sizeof(mgmt));
4344         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
4345                                           WLAN_FC_STYPE_DEAUTH);
4346         memcpy(mgmt.da, addr, ETH_ALEN);
4347         memcpy(mgmt.sa, own_addr, ETH_ALEN);
4348         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
4349         mgmt.u.deauth.reason_code = host_to_le16(reason);
4350         return wpa_driver_nl80211_send_mlme(drv, (u8 *) &mgmt,
4351                                             IEEE80211_HDRLEN +
4352                                             sizeof(mgmt.u.deauth));
4353 }
4354
4355
4356 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
4357                              int reason)
4358 {
4359         struct wpa_driver_nl80211_data *drv = priv;
4360         struct ieee80211_mgmt mgmt;
4361
4362         memset(&mgmt, 0, sizeof(mgmt));
4363         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
4364                                           WLAN_FC_STYPE_DISASSOC);
4365         memcpy(mgmt.da, addr, ETH_ALEN);
4366         memcpy(mgmt.sa, own_addr, ETH_ALEN);
4367         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
4368         mgmt.u.disassoc.reason_code = host_to_le16(reason);
4369         return wpa_driver_nl80211_send_mlme(drv, (u8 *) &mgmt,
4370                                             IEEE80211_HDRLEN +
4371                                             sizeof(mgmt.u.disassoc));
4372 }
4373
4374
4375 static void *i802_init(struct hostapd_data *hapd,
4376                        struct wpa_init_params *params)
4377 {
4378         struct wpa_driver_nl80211_data *drv;
4379         size_t i;
4380
4381         drv = wpa_driver_nl80211_init(hapd, params->ifname);
4382         if (drv == NULL)
4383                 return NULL;
4384
4385         drv->bss.ifindex = drv->ifindex;
4386
4387         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
4388         drv->if_indices = drv->default_if_indices;
4389         for (i = 0; i < params->num_bridge; i++) {
4390                 if (params->bridge[i])
4391                         add_ifidx(drv, if_nametoindex(params->bridge[i]));
4392         }
4393
4394         /* start listening for EAPOL on the default AP interface */
4395         add_ifidx(drv, drv->ifindex);
4396
4397         if (hostapd_set_iface_flags(drv, drv->ifname, 0))
4398                 goto failed;
4399
4400         if (params->bssid) {
4401                 if (set_ifhwaddr(drv, drv->ifname, params->bssid))
4402                         goto failed;
4403         }
4404
4405         if (wpa_driver_nl80211_set_mode(drv, IEEE80211_MODE_AP)) {
4406                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
4407                            "into AP mode", drv->ifname);
4408                 goto failed;
4409         }
4410
4411         if (hostapd_set_iface_flags(drv, drv->ifname, 1))
4412                 goto failed;
4413
4414         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
4415         if (drv->eapol_sock < 0) {
4416                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
4417                 goto failed;
4418         }
4419
4420         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
4421         {
4422                 printf("Could not register read socket for eapol\n");
4423                 goto failed;
4424         }
4425
4426         if (get_ifhwaddr(drv, drv->ifname, params->own_addr))
4427                 goto failed;
4428
4429         return drv;
4430
4431 failed:
4432         nl80211_remove_monitor_interface(drv);
4433         if (drv->ioctl_sock >= 0)
4434                 close(drv->ioctl_sock);
4435
4436         genl_family_put(drv->nl80211);
4437         nl_cache_free(drv->nl_cache);
4438         nl_handle_destroy(drv->nl_handle);
4439         nl_cb_put(drv->nl_cb);
4440
4441         os_free(drv);
4442         return NULL;
4443 }
4444
4445
4446 static void i802_deinit(void *priv)
4447 {
4448         wpa_driver_nl80211_deinit(priv);
4449 }
4450
4451 #endif /* HOSTAPD */
4452
4453
4454 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
4455         .name = "nl80211",
4456         .desc = "Linux nl80211/cfg80211",
4457         .get_bssid = wpa_driver_nl80211_get_bssid,
4458         .get_ssid = wpa_driver_nl80211_get_ssid,
4459         .set_key = wpa_driver_nl80211_set_key,
4460         .scan2 = wpa_driver_nl80211_scan,
4461         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
4462         .deauthenticate = wpa_driver_nl80211_deauthenticate,
4463         .disassociate = wpa_driver_nl80211_disassociate,
4464         .authenticate = wpa_driver_nl80211_authenticate,
4465         .associate = wpa_driver_nl80211_associate,
4466         .init = wpa_driver_nl80211_init,
4467         .deinit = wpa_driver_nl80211_deinit,
4468         .get_capa = wpa_driver_nl80211_get_capa,
4469         .set_operstate = wpa_driver_nl80211_set_operstate,
4470         .set_supp_port = wpa_driver_nl80211_set_supp_port,
4471         .set_country = wpa_driver_nl80211_set_country,
4472         .set_beacon = wpa_driver_nl80211_set_beacon,
4473 #if defined(CONFIG_AP) || defined(HOSTAPD)
4474         .send_mlme = wpa_driver_nl80211_send_mlme,
4475         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
4476         .sta_add = wpa_driver_nl80211_sta_add,
4477         .sta_remove = wpa_driver_nl80211_sta_remove,
4478         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
4479         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
4480 #endif /* CONFIG_AP || HOSTAPD */
4481 #ifdef HOSTAPD
4482         .hapd_init = i802_init,
4483         .hapd_deinit = i802_deinit,
4484         .get_seqnum = i802_get_seqnum,
4485         .flush = i802_flush,
4486         .read_sta_data = i802_read_sta_data,
4487         .sta_deauth = i802_sta_deauth,
4488         .sta_disassoc = i802_sta_disassoc,
4489         .get_inact_sec = i802_get_inact_sec,
4490         .sta_clear_stats = i802_sta_clear_stats,
4491         .set_freq = i802_set_freq,
4492         .set_rts = i802_set_rts,
4493         .set_frag = i802_set_frag,
4494         .set_rate_sets = i802_set_rate_sets,
4495         .set_cts_protect = i802_set_cts_protect,
4496         .set_preamble = i802_set_preamble,
4497         .set_short_slot_time = i802_set_short_slot_time,
4498         .set_tx_queue_params = i802_set_tx_queue_params,
4499         .bss_add = i802_bss_add,
4500         .bss_remove = i802_bss_remove,
4501         .if_add = i802_if_add,
4502         .if_update = i802_if_update,
4503         .if_remove = i802_if_remove,
4504         .set_sta_vlan = i802_set_sta_vlan,
4505 #endif /* HOSTAPD */
4506 };