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