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