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