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