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