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