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