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