nl80211: Merge hostapd and wpa_supplicant key configuration
[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 nl_set_encr(int ifindex, struct wpa_driver_nl80211_data *drv,
1401                        wpa_alg alg, const u8 *addr, int key_idx, int set_tx,
1402                        const u8 *seq, size_t seq_len,
1403                        const u8 *key, size_t key_len)
1404 {
1405         struct nl_msg *msg;
1406         int ret;
1407
1408         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
1409                    "set_tx=%d seq_len=%lu key_len=%lu",
1410                    __func__, ifindex, alg, addr, key_idx, set_tx,
1411                    (unsigned long) seq_len, (unsigned long) key_len);
1412
1413         msg = nlmsg_alloc();
1414         if (!msg)
1415                 return -ENOMEM;
1416
1417         if (alg == WPA_ALG_NONE) {
1418                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1419                             0, NL80211_CMD_DEL_KEY, 0);
1420         } else {
1421                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1422                             0, NL80211_CMD_NEW_KEY, 0);
1423                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
1424                 switch (alg) {
1425                 case WPA_ALG_WEP:
1426                         if (key_len == 5)
1427                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1428                                             0x000FAC01);
1429                         else
1430                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1431                                             0x000FAC05);
1432                         break;
1433                 case WPA_ALG_TKIP:
1434                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC02);
1435                         break;
1436                 case WPA_ALG_CCMP:
1437                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC04);
1438                         break;
1439                 case WPA_ALG_IGTK:
1440                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC06);
1441                         break;
1442                 default:
1443                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
1444                                    "algorithm %d", __func__, alg);
1445                         nlmsg_free(msg);
1446                         return -1;
1447                 }
1448         }
1449
1450         if (seq)
1451                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
1452
1453         if (addr && os_memcmp(addr, "\xff\xff\xff\xff\xff\xff", ETH_ALEN) != 0)
1454         {
1455                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
1456                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
1457         }
1458         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
1459         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
1460
1461         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1462         if (ret == -ENOENT && alg == WPA_ALG_NONE)
1463                 ret = 0;
1464         if (ret)
1465                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
1466                            ret, strerror(-ret));
1467
1468         /*
1469          * If we failed or don't need to set the default TX key (below),
1470          * we're done here.
1471          */
1472         if (ret || !set_tx || alg == WPA_ALG_NONE)
1473                 return ret;
1474 #ifdef HOSTAPD /* FIX: is this needed? */
1475         if (addr)
1476                 return ret;
1477 #endif /* HOSTAPD */
1478
1479         msg = nlmsg_alloc();
1480         if (!msg)
1481                 return -ENOMEM;
1482
1483         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1484                     0, NL80211_CMD_SET_KEY, 0);
1485         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
1486         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
1487         if (alg == WPA_ALG_IGTK)
1488                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
1489         else
1490                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
1491
1492         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1493         if (ret == -ENOENT)
1494                 ret = 0;
1495         if (ret)
1496                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
1497                            "err=%d %s)", ret, strerror(-ret));
1498         return ret;
1499
1500 nla_put_failure:
1501         return -ENOBUFS;
1502 }
1503
1504
1505 static int wpa_driver_nl80211_set_key(void *priv, wpa_alg alg,
1506                                       const u8 *addr, int key_idx,
1507                                       int set_tx, const u8 *seq,
1508                                       size_t seq_len,
1509                                       const u8 *key, size_t key_len)
1510 {
1511         struct wpa_driver_nl80211_data *drv = priv;
1512         return nl_set_encr(drv->ifindex, drv, alg, addr, key_idx, set_tx, seq,
1513                            seq_len, key, key_len);
1514 }
1515
1516
1517 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
1518                                    const u8 *addr, int cmd, u16 reason_code)
1519 {
1520         int ret = -1;
1521         struct nl_msg *msg;
1522
1523         msg = nlmsg_alloc();
1524         if (!msg)
1525                 return -1;
1526
1527         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0, cmd, 0);
1528
1529         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1530         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
1531         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
1532
1533         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1534         msg = NULL;
1535         if (ret) {
1536                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
1537                            "(%s)", ret, strerror(-ret));
1538                 goto nla_put_failure;
1539         }
1540         ret = 0;
1541
1542 nla_put_failure:
1543         nlmsg_free(msg);
1544         return ret;
1545 }
1546
1547
1548 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
1549                                              int reason_code)
1550 {
1551         struct wpa_driver_nl80211_data *drv = priv;
1552         wpa_printf(MSG_DEBUG, "%s", __func__);
1553         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
1554                                        reason_code);
1555 }
1556
1557
1558 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
1559                                            int reason_code)
1560 {
1561         struct wpa_driver_nl80211_data *drv = priv;
1562         wpa_printf(MSG_DEBUG, "%s", __func__);
1563         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
1564                                        reason_code);
1565 }
1566
1567
1568 static int wpa_driver_nl80211_authenticate(
1569         void *priv, struct wpa_driver_auth_params *params)
1570 {
1571         struct wpa_driver_nl80211_data *drv = priv;
1572         int ret = -1, i;
1573         struct nl_msg *msg;
1574         enum nl80211_auth_type type;
1575
1576         drv->associated = 0;
1577
1578         msg = nlmsg_alloc();
1579         if (!msg)
1580                 return -1;
1581
1582         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
1583                    drv->ifindex);
1584
1585         for (i = 0; i < 4; i++) {
1586                 if (!params->wep_key[i])
1587                         continue;
1588                 wpa_driver_nl80211_set_key(drv, WPA_ALG_WEP, NULL, i,
1589                                            i == params->wep_tx_keyidx, NULL, 0,
1590                                            params->wep_key[i],
1591                                            params->wep_key_len[i]);
1592         }
1593
1594         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1595                     NL80211_CMD_AUTHENTICATE, 0);
1596
1597         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1598         if (params->bssid) {
1599                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
1600                            MAC2STR(params->bssid));
1601                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
1602         }
1603         if (params->freq) {
1604                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
1605                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
1606         }
1607         if (params->ssid) {
1608                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
1609                                   params->ssid, params->ssid_len);
1610                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
1611                         params->ssid);
1612         }
1613         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
1614         if (params->ie)
1615                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
1616         /*
1617          * TODO: if multiple auth_alg options enabled, try them one by one if
1618          * the AP rejects authentication due to unknown auth alg
1619          */
1620         if (params->auth_alg & AUTH_ALG_OPEN_SYSTEM)
1621                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
1622         else if (params->auth_alg & AUTH_ALG_SHARED_KEY)
1623                 type = NL80211_AUTHTYPE_SHARED_KEY;
1624         else if (params->auth_alg & AUTH_ALG_LEAP)
1625                 type = NL80211_AUTHTYPE_NETWORK_EAP;
1626         else if (params->auth_alg & AUTH_ALG_FT)
1627                 type = NL80211_AUTHTYPE_FT;
1628         else
1629                 goto nla_put_failure;
1630         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
1631         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
1632
1633         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1634         msg = NULL;
1635         if (ret) {
1636                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
1637                            "(%s)", ret, strerror(-ret));
1638                 goto nla_put_failure;
1639         }
1640         ret = 0;
1641         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
1642                    "successfully");
1643
1644 nla_put_failure:
1645         nlmsg_free(msg);
1646         return ret;
1647 }
1648
1649
1650 #if defined(CONFIG_AP) || defined(HOSTAPD)
1651
1652 struct phy_info_arg {
1653         u16 *num_modes;
1654         struct hostapd_hw_modes *modes;
1655 };
1656
1657 static int phy_info_handler(struct nl_msg *msg, void *arg)
1658 {
1659         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
1660         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1661         struct phy_info_arg *phy_info = arg;
1662
1663         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
1664
1665         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
1666         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
1667                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
1668                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
1669                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
1670                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
1671                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
1672                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
1673         };
1674
1675         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
1676         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
1677                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
1678                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
1679         };
1680
1681         struct nlattr *nl_band;
1682         struct nlattr *nl_freq;
1683         struct nlattr *nl_rate;
1684         int rem_band, rem_freq, rem_rate;
1685         struct hostapd_hw_modes *mode;
1686         int idx, mode_is_set;
1687
1688         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1689                   genlmsg_attrlen(gnlh, 0), NULL);
1690
1691         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
1692                 return NL_SKIP;
1693
1694         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
1695                 mode = realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
1696                 if (!mode)
1697                         return NL_SKIP;
1698                 phy_info->modes = mode;
1699
1700                 mode_is_set = 0;
1701
1702                 mode = &phy_info->modes[*(phy_info->num_modes)];
1703                 memset(mode, 0, sizeof(*mode));
1704                 *(phy_info->num_modes) += 1;
1705
1706                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
1707                           nla_len(nl_band), NULL);
1708
1709                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
1710                         mode->ht_capab = nla_get_u16(
1711                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
1712                 }
1713
1714                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
1715                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
1716                                   nla_len(nl_freq), freq_policy);
1717                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
1718                                 continue;
1719                         mode->num_channels++;
1720                 }
1721
1722                 mode->channels = calloc(mode->num_channels, sizeof(struct hostapd_channel_data));
1723                 if (!mode->channels)
1724                         return NL_SKIP;
1725
1726                 idx = 0;
1727
1728                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
1729                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
1730                                   nla_len(nl_freq), freq_policy);
1731                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
1732                                 continue;
1733
1734                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
1735                         mode->channels[idx].flag = 0;
1736
1737                         if (!mode_is_set) {
1738                                 /* crude heuristic */
1739                                 if (mode->channels[idx].freq < 4000)
1740                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
1741                                 else
1742                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
1743                                 mode_is_set = 1;
1744                         }
1745
1746                         /* crude heuristic */
1747                         if (mode->channels[idx].freq < 4000)
1748                                 if (mode->channels[idx].freq == 2484)
1749                                         mode->channels[idx].chan = 14;
1750                                 else
1751                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
1752                         else
1753                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
1754
1755                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
1756                                 mode->channels[idx].flag |=
1757                                         HOSTAPD_CHAN_DISABLED;
1758                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
1759                                 mode->channels[idx].flag |=
1760                                         HOSTAPD_CHAN_PASSIVE_SCAN;
1761                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
1762                                 mode->channels[idx].flag |=
1763                                         HOSTAPD_CHAN_NO_IBSS;
1764                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
1765                                 mode->channels[idx].flag |=
1766                                         HOSTAPD_CHAN_RADAR;
1767
1768                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
1769                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
1770                                 mode->channels[idx].max_tx_power =
1771                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
1772
1773                         idx++;
1774                 }
1775
1776                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
1777                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
1778                                   nla_len(nl_rate), rate_policy);
1779                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
1780                                 continue;
1781                         mode->num_rates++;
1782                 }
1783
1784                 mode->rates = calloc(mode->num_rates, sizeof(struct hostapd_rate_data));
1785                 if (!mode->rates)
1786                         return NL_SKIP;
1787
1788                 idx = 0;
1789
1790                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
1791                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
1792                                   nla_len(nl_rate), rate_policy);
1793                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
1794                                 continue;
1795                         mode->rates[idx].rate = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
1796
1797                         /* crude heuristic */
1798                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
1799                             mode->rates[idx].rate > 200)
1800                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
1801
1802                         if (tb_rate[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE])
1803                                 mode->rates[idx].flags |= HOSTAPD_RATE_PREAMBLE2;
1804
1805                         idx++;
1806                 }
1807         }
1808
1809         return NL_SKIP;
1810 }
1811
1812 static struct hostapd_hw_modes *
1813 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
1814 {
1815         u16 m;
1816         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
1817         int i, mode11g_idx = -1;
1818
1819         /* If only 802.11g mode is included, use it to construct matching
1820          * 802.11b mode data. */
1821
1822         for (m = 0; m < *num_modes; m++) {
1823                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
1824                         return modes; /* 802.11b already included */
1825                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
1826                         mode11g_idx = m;
1827         }
1828
1829         if (mode11g_idx < 0)
1830                 return modes; /* 2.4 GHz band not supported at all */
1831
1832         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
1833         if (nmodes == NULL)
1834                 return modes; /* Could not add 802.11b mode */
1835
1836         mode = &nmodes[*num_modes];
1837         os_memset(mode, 0, sizeof(*mode));
1838         (*num_modes)++;
1839         modes = nmodes;
1840
1841         mode->mode = HOSTAPD_MODE_IEEE80211B;
1842
1843         mode11g = &modes[mode11g_idx];
1844         mode->num_channels = mode11g->num_channels;
1845         mode->channels = os_malloc(mode11g->num_channels *
1846                                    sizeof(struct hostapd_channel_data));
1847         if (mode->channels == NULL) {
1848                 (*num_modes)--;
1849                 return modes; /* Could not add 802.11b mode */
1850         }
1851         os_memcpy(mode->channels, mode11g->channels,
1852                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
1853
1854         mode->num_rates = 0;
1855         mode->rates = os_malloc(4 * sizeof(struct hostapd_rate_data));
1856         if (mode->rates == NULL) {
1857                 os_free(mode->channels);
1858                 (*num_modes)--;
1859                 return modes; /* Could not add 802.11b mode */
1860         }
1861
1862         for (i = 0; i < mode11g->num_rates; i++) {
1863                 if (mode11g->rates[i].rate > 110 ||
1864                     mode11g->rates[i].flags &
1865                     (HOSTAPD_RATE_ERP | HOSTAPD_RATE_OFDM))
1866                         continue;
1867                 mode->rates[mode->num_rates] = mode11g->rates[i];
1868                 mode->num_rates++;
1869                 if (mode->num_rates == 4)
1870                         break;
1871         }
1872
1873         if (mode->num_rates == 0) {
1874                 os_free(mode->channels);
1875                 os_free(mode->rates);
1876                 (*num_modes)--;
1877                 return modes; /* No 802.11b rates */
1878         }
1879
1880         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
1881                    "information");
1882
1883         return modes;
1884 }
1885
1886
1887 static struct hostapd_hw_modes *
1888 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
1889 {
1890         struct wpa_driver_nl80211_data *drv = priv;
1891         struct nl_msg *msg;
1892         struct phy_info_arg result = {
1893                 .num_modes = num_modes,
1894                 .modes = NULL,
1895         };
1896
1897         *num_modes = 0;
1898         *flags = 0;
1899
1900         msg = nlmsg_alloc();
1901         if (!msg)
1902                 return NULL;
1903
1904         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1905                     0, NL80211_CMD_GET_WIPHY, 0);
1906
1907         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1908
1909         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0)
1910                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
1911  nla_put_failure:
1912         return NULL;
1913 }
1914
1915 #endif /* CONFIG_AP || HOSTAPD */
1916
1917
1918 #ifdef CONFIG_AP
1919
1920 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
1921                                          const void *data, size_t len,
1922                                          int encrypt)
1923 {
1924         __u8 rtap_hdr[] = {
1925                 0x00, 0x00, /* radiotap version */
1926                 0x0e, 0x00, /* radiotap length */
1927                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
1928                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
1929                 0x00,       /* padding */
1930                 0x00, 0x00, /* RX and TX flags to indicate that */
1931                 0x00, 0x00, /* this is the injected frame directly */
1932         };
1933         struct iovec iov[2] = {
1934                 {
1935                         .iov_base = &rtap_hdr,
1936                         .iov_len = sizeof(rtap_hdr),
1937                 },
1938                 {
1939                         .iov_base = (void *) data,
1940                         .iov_len = len,
1941                 }
1942         };
1943         struct msghdr msg = {
1944                 .msg_name = NULL,
1945                 .msg_namelen = 0,
1946                 .msg_iov = iov,
1947                 .msg_iovlen = 2,
1948                 .msg_control = NULL,
1949                 .msg_controllen = 0,
1950                 .msg_flags = 0,
1951         };
1952
1953         if (encrypt)
1954                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
1955
1956         return sendmsg(drv->monitor_sock, &msg, 0);
1957 }
1958
1959
1960 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
1961                                         size_t data_len)
1962 {
1963         struct wpa_driver_nl80211_data *drv = priv;
1964         struct ieee80211_mgmt *mgmt;
1965         int do_not_encrypt = 0;
1966         u16 fc;
1967
1968         mgmt = (struct ieee80211_mgmt *) data;
1969         fc = le_to_host16(mgmt->frame_control);
1970
1971         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
1972             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
1973                 /*
1974                  * Only one of the authentication frame types is encrypted.
1975                  * In order for static WEP encryption to work properly (i.e.,
1976                  * to not encrypt the frame), we need to tell mac80211 about
1977                  * the frames that must not be encrypted.
1978                  */
1979                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
1980                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
1981                 if (auth_alg == WLAN_AUTH_OPEN ||
1982                     (auth_alg == WLAN_AUTH_SHARED_KEY && auth_trans != 3))
1983                         do_not_encrypt = 1;
1984         }
1985
1986         return wpa_driver_nl80211_send_frame(drv, data, data_len,
1987                                              !do_not_encrypt);
1988 }
1989
1990
1991 static int wpa_driver_nl80211_set_beacon(void *priv,
1992                                          const u8 *head, size_t head_len,
1993                                          const u8 *tail, size_t tail_len,
1994                                          int dtim_period)
1995 {
1996         struct wpa_driver_nl80211_data *drv = priv;
1997         struct nl_msg *msg;
1998         u8 cmd = NL80211_CMD_NEW_BEACON;
1999         int ret;
2000
2001         msg = nlmsg_alloc();
2002         if (!msg)
2003                 return -ENOMEM;
2004
2005         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
2006                    drv->beacon_set);
2007         if (drv->beacon_set)
2008                 cmd = NL80211_CMD_SET_BEACON;
2009
2010         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2011                     0, cmd, 0);
2012         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
2013         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
2014         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2015         if (!drv->beacon_int)
2016                 drv->beacon_int = 100;
2017         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, drv->beacon_int);
2018         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
2019
2020         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2021         if (ret) {
2022                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
2023                            ret, strerror(-ret));
2024         } else
2025                 drv->beacon_set = 1;
2026         return ret;
2027  nla_put_failure:
2028         return -ENOBUFS;
2029 }
2030
2031
2032 static int wpa_driver_nl80211_set_beacon_int(void *priv, int value)
2033 {
2034         struct wpa_driver_nl80211_data *drv = priv;
2035         struct nl_msg *msg;
2036
2037         drv->beacon_int = value;
2038
2039         if (!drv->beacon_set)
2040                 return 0;
2041
2042         msg = nlmsg_alloc();
2043         if (!msg)
2044                 return -ENOMEM;
2045
2046         wpa_printf(MSG_DEBUG, "nl80211: Set beacon interval %d "
2047                    "(beacon_set=%d)", value, drv->beacon_set);
2048         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2049                     0, NL80211_CMD_SET_BEACON, 0);
2050         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2051
2052         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, value);
2053
2054         return send_and_recv_msgs(drv, msg, NULL, NULL);
2055  nla_put_failure:
2056         return -ENOBUFS;
2057 }
2058
2059
2060 static int wpa_driver_nl80211_set_freq2(
2061         struct wpa_driver_nl80211_data *drv,
2062         struct wpa_driver_associate_params *params)
2063 {
2064         struct nl_msg *msg;
2065         int ret;
2066
2067         msg = nlmsg_alloc();
2068         if (!msg)
2069                 return -1;
2070
2071         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2072                     NL80211_CMD_SET_WIPHY, 0);
2073
2074         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2075
2076         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
2077
2078         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2079         if (ret == 0)
2080                 return 0;
2081         wpa_printf(MSG_DEBUG, "nl80211: MLME Failed to set channel (freq=%d): "
2082                    "%d (%s)", params->freq, ret, strerror(-ret));
2083 nla_put_failure:
2084         return -1;
2085 }
2086
2087
2088 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
2089                                  int ifidx)
2090 {
2091         struct nl_msg *msg;
2092
2093         msg = nlmsg_alloc();
2094         if (!msg)
2095                 goto nla_put_failure;
2096
2097         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2098                     0, NL80211_CMD_DEL_INTERFACE, 0);
2099         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
2100
2101         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
2102                 return;
2103  nla_put_failure:
2104         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d).\n",
2105                    ifidx);
2106 }
2107
2108
2109 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
2110                                 const char *ifname, enum nl80211_iftype iftype)
2111 {
2112         struct nl_msg *msg, *flags = NULL;
2113         int ifidx;
2114         int ret = -ENOBUFS;
2115
2116         msg = nlmsg_alloc();
2117         if (!msg)
2118                 return -1;
2119
2120         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2121                     0, NL80211_CMD_NEW_INTERFACE, 0);
2122         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2123         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
2124         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
2125
2126         if (iftype == NL80211_IFTYPE_MONITOR) {
2127                 int err;
2128
2129                 flags = nlmsg_alloc();
2130                 if (!flags)
2131                         goto nla_put_failure;
2132
2133                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
2134
2135                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
2136
2137                 nlmsg_free(flags);
2138
2139                 if (err)
2140                         goto nla_put_failure;
2141         }
2142
2143         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2144         if (ret) {
2145  nla_put_failure:
2146                 wpa_printf(MSG_ERROR, "Failed to create interface %s.",
2147                            ifname);
2148                 return ret;
2149         }
2150
2151         ifidx = if_nametoindex(ifname);
2152
2153         if (ifidx <= 0)
2154                 return -1;
2155
2156         return ifidx;
2157 }
2158
2159
2160 enum ieee80211_msg_type {
2161         ieee80211_msg_normal = 0,
2162         ieee80211_msg_tx_callback_ack = 1,
2163         ieee80211_msg_tx_callback_fail = 2,
2164 };
2165
2166
2167 void ap_tx_status(void *ctx, const u8 *addr,
2168                   const u8 *buf, size_t len, int ack);
2169 void ap_rx_from_unknown_sta(void *ctx, const u8 *addr);
2170 void ap_mgmt_rx(void *ctx, u8 *buf, size_t len, u16 stype,
2171                 struct hostapd_frame_info *fi);
2172 void ap_mgmt_tx_cb(void *ctx, u8 *buf, size_t len, u16 stype, int ok);
2173
2174
2175 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
2176 {
2177         struct ieee80211_hdr *hdr;
2178         u16 fc, type, stype;
2179
2180         hdr = (struct ieee80211_hdr *) buf;
2181         fc = le_to_host16(hdr->frame_control);
2182
2183         type = WLAN_FC_GET_TYPE(fc);
2184         stype = WLAN_FC_GET_STYPE(fc);
2185
2186         switch (type) {
2187         case WLAN_FC_TYPE_MGMT:
2188                 wpa_printf(MSG_DEBUG, "MGMT (TX callback) %s",
2189                            ok ? "ACK" : "fail");
2190                 ap_mgmt_tx_cb(ctx, buf, len, stype, ok);
2191                 break;
2192         case WLAN_FC_TYPE_CTRL:
2193                 wpa_printf(MSG_DEBUG, "CTRL (TX callback) %s",
2194                            ok ? "ACK" : "fail");
2195                 break;
2196         case WLAN_FC_TYPE_DATA:
2197                 ap_tx_status(ctx, hdr->addr1, buf, len, ok);
2198                 break;
2199         default:
2200                 wpa_printf(MSG_DEBUG, "unknown TX callback frame type %d",
2201                            type);
2202                 break;
2203         }
2204 }
2205
2206
2207 static void handle_frame(struct wpa_driver_nl80211_data *drv,
2208                          u8 *buf, size_t len,
2209                          struct hostapd_frame_info *hfi,
2210                          enum ieee80211_msg_type msg_type)
2211 {
2212         struct ieee80211_hdr *hdr;
2213         u16 fc, type, stype;
2214         size_t data_len = len;
2215
2216         /*
2217          * PS-Poll frames are 16 bytes. All other frames are
2218          * 24 bytes or longer.
2219          */
2220         if (len < 16)
2221                 return;
2222
2223         hdr = (struct ieee80211_hdr *) buf;
2224         fc = le_to_host16(hdr->frame_control);
2225
2226         type = WLAN_FC_GET_TYPE(fc);
2227         stype = WLAN_FC_GET_STYPE(fc);
2228
2229         switch (type) {
2230         case WLAN_FC_TYPE_DATA:
2231                 if (len < 24)
2232                         return;
2233                 switch (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) {
2234                 case WLAN_FC_TODS:
2235                         break;
2236                 case WLAN_FC_FROMDS:
2237                         break;
2238                 default:
2239                         /* discard */
2240                         return;
2241                 }
2242                 break;
2243         case WLAN_FC_TYPE_CTRL:
2244                 /* discard non-ps-poll frames */
2245                 if (stype != WLAN_FC_STYPE_PSPOLL)
2246                         return;
2247                 break;
2248         case WLAN_FC_TYPE_MGMT:
2249                 break;
2250         default:
2251                 /* discard */
2252                 return;
2253         }
2254
2255         switch (msg_type) {
2256         case ieee80211_msg_normal:
2257                 /* continue processing */
2258                 break;
2259         case ieee80211_msg_tx_callback_ack:
2260                 handle_tx_callback(drv->ctx, buf, data_len, 1);
2261                 return;
2262         case ieee80211_msg_tx_callback_fail:
2263                 handle_tx_callback(drv->ctx, buf, data_len, 0);
2264                 return;
2265         }
2266
2267         switch (type) {
2268         case WLAN_FC_TYPE_MGMT:
2269                 if (stype != WLAN_FC_STYPE_BEACON &&
2270                     stype != WLAN_FC_STYPE_PROBE_REQ)
2271                         wpa_printf(MSG_MSGDUMP, "MGMT");
2272                 ap_mgmt_rx(drv->ctx, buf, data_len, stype, hfi);
2273                 break;
2274         case WLAN_FC_TYPE_CTRL:
2275                 /* can only get here with PS-Poll frames */
2276                 wpa_printf(MSG_DEBUG, "CTRL");
2277                 ap_rx_from_unknown_sta(drv->ctx, hdr->addr2);
2278                 break;
2279         case WLAN_FC_TYPE_DATA:
2280                 ap_rx_from_unknown_sta(drv->ctx, hdr->addr2);
2281                 break;
2282         }
2283 }
2284
2285
2286 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
2287 {
2288         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2289         int len;
2290         unsigned char buf[3000];
2291         struct ieee80211_radiotap_iterator iter;
2292         int ret;
2293         struct hostapd_frame_info hfi;
2294         int injected = 0, failed = 0, msg_type, rxflags = 0;
2295
2296         len = recv(sock, buf, sizeof(buf), 0);
2297         if (len < 0) {
2298                 perror("recv");
2299                 return;
2300         }
2301
2302         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
2303                 printf("received invalid radiotap frame\n");
2304                 return;
2305         }
2306
2307         memset(&hfi, 0, sizeof(hfi));
2308
2309         while (1) {
2310                 ret = ieee80211_radiotap_iterator_next(&iter);
2311                 if (ret == -ENOENT)
2312                         break;
2313                 if (ret) {
2314                         printf("received invalid radiotap frame (%d)\n", ret);
2315                         return;
2316                 }
2317                 switch (iter.this_arg_index) {
2318                 case IEEE80211_RADIOTAP_FLAGS:
2319                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
2320                                 len -= 4;
2321                         break;
2322                 case IEEE80211_RADIOTAP_RX_FLAGS:
2323                         rxflags = 1;
2324                         break;
2325                 case IEEE80211_RADIOTAP_TX_FLAGS:
2326                         injected = 1;
2327                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
2328                                         IEEE80211_RADIOTAP_F_TX_FAIL;
2329                         break;
2330                 case IEEE80211_RADIOTAP_DATA_RETRIES:
2331                         break;
2332                 case IEEE80211_RADIOTAP_CHANNEL:
2333                         /* TODO convert from freq/flags to channel number
2334                         hfi.channel = XXX;
2335                         hfi.phytype = XXX;
2336                          */
2337                         break;
2338                 case IEEE80211_RADIOTAP_RATE:
2339                         hfi.datarate = *iter.this_arg * 5;
2340                         break;
2341                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
2342                         hfi.ssi_signal = *iter.this_arg;
2343                         break;
2344                 }
2345         }
2346
2347         if (rxflags && injected)
2348                 return;
2349
2350         if (!injected)
2351                 msg_type = ieee80211_msg_normal;
2352         else if (failed)
2353                 msg_type = ieee80211_msg_tx_callback_fail;
2354         else
2355                 msg_type = ieee80211_msg_tx_callback_ack;
2356
2357         handle_frame(drv, buf + iter.max_length,
2358                      len - iter.max_length, &hfi, msg_type);
2359 }
2360
2361
2362 /*
2363  * we post-process the filter code later and rewrite
2364  * this to the offset to the last instruction
2365  */
2366 #define PASS    0xFF
2367 #define FAIL    0xFE
2368
2369 static struct sock_filter msock_filter_insns[] = {
2370         /*
2371          * do a little-endian load of the radiotap length field
2372          */
2373         /* load lower byte into A */
2374         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
2375         /* put it into X (== index register) */
2376         BPF_STMT(BPF_MISC| BPF_TAX, 0),
2377         /* load upper byte into A */
2378         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
2379         /* left-shift it by 8 */
2380         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
2381         /* or with X */
2382         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
2383         /* put result into X */
2384         BPF_STMT(BPF_MISC| BPF_TAX, 0),
2385
2386         /*
2387          * Allow management frames through, this also gives us those
2388          * management frames that we sent ourselves with status
2389          */
2390         /* load the lower byte of the IEEE 802.11 frame control field */
2391         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
2392         /* mask off frame type and version */
2393         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
2394         /* accept frame if it's both 0, fall through otherwise */
2395         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
2396
2397         /*
2398          * TODO: add a bit to radiotap RX flags that indicates
2399          * that the sending station is not associated, then
2400          * add a filter here that filters on our DA and that flag
2401          * to allow us to deauth frames to that bad station.
2402          *
2403          * Not a regression -- we didn't do it before either.
2404          */
2405
2406 #if 0
2407         /*
2408          * drop non-data frames, WDS frames
2409          */
2410         /* load the lower byte of the frame control field */
2411         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
2412         /* mask off QoS bit */
2413         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
2414         /* drop non-data frames */
2415         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
2416         /* load the upper byte of the frame control field */
2417         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
2418         /* mask off toDS/fromDS */
2419         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
2420         /* drop WDS frames */
2421         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, FAIL, 0),
2422 #endif
2423
2424         /*
2425          * add header length to index
2426          */
2427         /* load the lower byte of the frame control field */
2428         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
2429         /* mask off QoS bit */
2430         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
2431         /* right shift it by 6 to give 0 or 2 */
2432         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
2433         /* add data frame header length */
2434         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
2435         /* add index, was start of 802.11 header */
2436         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
2437         /* move to index, now start of LL header */
2438         BPF_STMT(BPF_MISC | BPF_TAX, 0),
2439
2440         /*
2441          * Accept empty data frames, we use those for
2442          * polling activity.
2443          */
2444         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
2445         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
2446
2447         /*
2448          * Accept EAPOL frames
2449          */
2450         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
2451         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
2452         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
2453         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
2454
2455         /* keep these last two statements or change the code below */
2456         /* return 0 == "DROP" */
2457         BPF_STMT(BPF_RET | BPF_K, 0),
2458         /* return ~0 == "keep all" */
2459         BPF_STMT(BPF_RET | BPF_K, ~0),
2460 };
2461
2462 static struct sock_fprog msock_filter = {
2463         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
2464         .filter = msock_filter_insns,
2465 };
2466
2467
2468 static int add_monitor_filter(int s)
2469 {
2470         int idx;
2471
2472         /* rewrite all PASS/FAIL jump offsets */
2473         for (idx = 0; idx < msock_filter.len; idx++) {
2474                 struct sock_filter *insn = &msock_filter_insns[idx];
2475
2476                 if (BPF_CLASS(insn->code) == BPF_JMP) {
2477                         if (insn->code == (BPF_JMP|BPF_JA)) {
2478                                 if (insn->k == PASS)
2479                                         insn->k = msock_filter.len - idx - 2;
2480                                 else if (insn->k == FAIL)
2481                                         insn->k = msock_filter.len - idx - 3;
2482                         }
2483
2484                         if (insn->jt == PASS)
2485                                 insn->jt = msock_filter.len - idx - 2;
2486                         else if (insn->jt == FAIL)
2487                                 insn->jt = msock_filter.len - idx - 3;
2488
2489                         if (insn->jf == PASS)
2490                                 insn->jf = msock_filter.len - idx - 2;
2491                         else if (insn->jf == FAIL)
2492                                 insn->jf = msock_filter.len - idx - 3;
2493                 }
2494         }
2495
2496         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
2497                        &msock_filter, sizeof(msock_filter))) {
2498                 perror("SO_ATTACH_FILTER");
2499                 return -1;
2500         }
2501
2502         return 0;
2503 }
2504
2505
2506 static int
2507 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
2508 {
2509         char buf[IFNAMSIZ];
2510         struct sockaddr_ll ll;
2511         int optval;
2512         socklen_t optlen;
2513         int flags;
2514
2515         snprintf(buf, IFNAMSIZ, "mon.%s", drv->ifname);
2516         buf[IFNAMSIZ - 1] = '\0';
2517
2518         drv->monitor_ifidx =
2519                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR);
2520
2521         if (drv->monitor_ifidx < 0)
2522                 return -1;
2523
2524         if (wpa_driver_nl80211_get_ifflags_ifname(drv, buf, &flags) != 0) {
2525                 wpa_printf(MSG_ERROR, "Could not get interface '%s' flags",
2526                            buf);
2527                 goto error;
2528         }
2529         if (!(flags & IFF_UP)) {
2530                 if (wpa_driver_nl80211_set_ifflags_ifname(drv, buf,
2531                                                           flags | IFF_UP) != 0)
2532                 {
2533                         wpa_printf(MSG_ERROR, "Could not set interface '%s' "
2534                                    "UP", buf);
2535                         goto error;
2536                 }
2537         }
2538
2539         memset(&ll, 0, sizeof(ll));
2540         ll.sll_family = AF_PACKET;
2541         ll.sll_ifindex = drv->monitor_ifidx;
2542         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
2543         if (drv->monitor_sock < 0) {
2544                 perror("socket[PF_PACKET,SOCK_RAW]");
2545                 goto error;
2546         }
2547
2548         if (add_monitor_filter(drv->monitor_sock)) {
2549                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
2550                            "interface; do filtering in user space");
2551                 /* This works, but will cost in performance. */
2552         }
2553
2554         if (bind(drv->monitor_sock, (struct sockaddr *) &ll,
2555                  sizeof(ll)) < 0) {
2556                 perror("monitor socket bind");
2557                 goto error;
2558         }
2559
2560         optlen = sizeof(optval);
2561         optval = 20;
2562         if (setsockopt
2563             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
2564                 perror("Failed to set socket priority");
2565                 goto error;
2566         }
2567
2568         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
2569                                      drv, NULL)) {
2570                 printf("Could not register monitor read socket\n");
2571                 goto error;
2572         }
2573
2574         return 0;
2575  error:
2576         nl80211_remove_iface(drv, drv->monitor_ifidx);
2577         return -1;
2578 }
2579
2580
2581 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
2582                                  struct wpa_driver_associate_params *params)
2583 {
2584         if (drv->monitor_ifidx < 0 &&
2585             nl80211_create_monitor_interface(drv))
2586                 return -1;
2587
2588         if (wpa_driver_nl80211_set_mode(drv, params->mode) ||
2589             wpa_driver_nl80211_set_freq2(drv, params)) {
2590                 nl80211_remove_iface(drv, drv->monitor_ifidx);
2591                 drv->monitor_ifidx = -1;
2592                 return -1;
2593         }
2594
2595         /* TODO: setup monitor interface (and add code somewhere to remove this
2596          * when AP mode is stopped; associate with mode != 2 or drv_deinit) */
2597
2598         return 0;
2599 }
2600 #endif /* CONFIG_AP */
2601
2602
2603 static int wpa_driver_nl80211_associate(
2604         void *priv, struct wpa_driver_associate_params *params)
2605 {
2606         struct wpa_driver_nl80211_data *drv = priv;
2607         int ret = -1;
2608         struct nl_msg *msg;
2609
2610 #ifdef CONFIG_AP
2611         if (params->mode == 2)
2612                 return wpa_driver_nl80211_ap(drv, params);
2613 #endif /* CONFIG_AP */
2614
2615         wpa_driver_nl80211_set_auth_param(drv, IW_AUTH_DROP_UNENCRYPTED,
2616                                           params->drop_unencrypted);
2617
2618         drv->associated = 0;
2619
2620         msg = nlmsg_alloc();
2621         if (!msg)
2622                 return -1;
2623
2624         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
2625                    drv->ifindex);
2626         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2627                     NL80211_CMD_ASSOCIATE, 0);
2628
2629         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2630         if (params->bssid) {
2631                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
2632                            MAC2STR(params->bssid));
2633                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
2634         }
2635         if (params->freq) {
2636                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
2637                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
2638         }
2639         if (params->ssid) {
2640                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
2641                                   params->ssid, params->ssid_len);
2642                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
2643                         params->ssid);
2644                 if (params->ssid_len > sizeof(drv->ssid))
2645                         goto nla_put_failure;
2646                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
2647                 drv->ssid_len = params->ssid_len;
2648         }
2649         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
2650         if (params->wpa_ie)
2651                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
2652                         params->wpa_ie);
2653
2654         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2655         msg = NULL;
2656         if (ret) {
2657                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
2658                            "(%s)", ret, strerror(-ret));
2659                 goto nla_put_failure;
2660         }
2661         ret = 0;
2662         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
2663                    "successfully");
2664
2665 nla_put_failure:
2666         nlmsg_free(msg);
2667         return ret;
2668 }
2669
2670
2671 /**
2672  * wpa_driver_nl80211_set_mode - Set wireless mode (infra/adhoc)
2673  * @drv: Pointer to private driver data from wpa_driver_nl80211_init()
2674  * @mode: 0 = infra/BSS (associate with an AP), 1 = adhoc/IBSS
2675  * Returns: 0 on success, -1 on failure
2676  */
2677 static int wpa_driver_nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
2678                                        int mode)
2679 {
2680         int ret = -1, flags;
2681         struct nl_msg *msg;
2682         int nlmode;
2683
2684         switch (mode) {
2685         case 0:
2686                 nlmode = NL80211_IFTYPE_STATION;
2687                 break;
2688         case 1:
2689                 nlmode = NL80211_IFTYPE_ADHOC;
2690                 break;
2691         case 2:
2692                 nlmode = NL80211_IFTYPE_AP;
2693                 break;
2694         default:
2695                 return -1;
2696         }
2697
2698         msg = nlmsg_alloc();
2699         if (!msg)
2700                 return -1;
2701
2702         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2703                     0, NL80211_CMD_SET_INTERFACE, 0);
2704         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2705         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, nlmode);
2706
2707         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2708         if (!ret)
2709                 return 0;
2710         else
2711                 goto try_again;
2712
2713 nla_put_failure:
2714         wpa_printf(MSG_ERROR, "nl80211: Failed to set interface mode: %d (%s)",
2715                    ret, strerror(-ret));
2716         return -1;
2717
2718 try_again:
2719         /* mac80211 doesn't allow mode changes while the device is up, so
2720          * take the device down, try to set the mode again, and bring the
2721          * device back up.
2722          */
2723         if (wpa_driver_nl80211_get_ifflags(drv, &flags) == 0) {
2724                 (void) wpa_driver_nl80211_set_ifflags(drv, flags & ~IFF_UP);
2725
2726                 /* Try to set the mode again while the interface is down */
2727                 msg = nlmsg_alloc();
2728                 if (!msg)
2729                         return -1;
2730
2731                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2732                             0, NL80211_CMD_SET_INTERFACE, 0);
2733                 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2734                 NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, nlmode);
2735                 ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2736                 if (ret) {
2737                         wpa_printf(MSG_ERROR, "Failed to set interface %s "
2738                                    "mode(try_again): %d (%s)",
2739                                    drv->ifname, ret, strerror(-ret));
2740                 }
2741
2742                 /* Ignore return value of get_ifflags to ensure that the device
2743                  * is always up like it was before this function was called.
2744                  */
2745                 (void) wpa_driver_nl80211_get_ifflags(drv, &flags);
2746                 (void) wpa_driver_nl80211_set_ifflags(drv, flags | IFF_UP);
2747         }
2748
2749         return ret;
2750 }
2751
2752
2753 static int wpa_driver_nl80211_get_capa(void *priv,
2754                                        struct wpa_driver_capa *capa)
2755 {
2756         struct wpa_driver_nl80211_data *drv = priv;
2757         if (!drv->has_capability)
2758                 return -1;
2759         os_memcpy(capa, &drv->capa, sizeof(*capa));
2760         return 0;
2761 }
2762
2763
2764 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
2765 {
2766         struct wpa_driver_nl80211_data *drv = priv;
2767
2768         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
2769                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
2770         drv->operstate = state;
2771         return wpa_driver_nl80211_send_oper_ifla(
2772                 drv, -1, state ? IF_OPER_UP : IF_OPER_DORMANT);
2773 }
2774
2775
2776 #ifdef HOSTAPD
2777
2778 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
2779
2780 enum ieee80211_msg_type {
2781         ieee80211_msg_normal = 0,
2782         ieee80211_msg_tx_callback_ack = 1,
2783         ieee80211_msg_tx_callback_fail = 2,
2784 };
2785
2786
2787 static int i802_sta_deauth(void *priv, const u8 *addr, int reason);
2788 static int i802_sta_disassoc(void *priv, const u8 *addr, int reason);
2789
2790
2791 static struct i802_bss * get_bss(struct wpa_driver_nl80211_data *drv,
2792                                  const char *iface)
2793 {
2794         struct i802_bss *bss = &drv->bss;
2795         while (bss) {
2796                 if (os_strncmp(iface, bss->ifname, IFNAMSIZ) == 0)
2797                         return bss;
2798                 bss = bss->next;
2799         }
2800         wpa_printf(MSG_DEBUG, "nl80211: get_bss(%s) failed", iface);
2801         return NULL;
2802 }
2803
2804
2805 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
2806 {
2807         int i;
2808         int *old;
2809
2810         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
2811                    ifidx);
2812         for (i = 0; i < drv->num_if_indices; i++) {
2813                 if (drv->if_indices[i] == 0) {
2814                         drv->if_indices[i] = ifidx;
2815                         return;
2816                 }
2817         }
2818
2819         if (drv->if_indices != drv->default_if_indices)
2820                 old = drv->if_indices;
2821         else
2822                 old = NULL;
2823
2824         drv->if_indices = realloc(old,
2825                                   sizeof(int) * (drv->num_if_indices + 1));
2826         if (!drv->if_indices) {
2827                 if (!old)
2828                         drv->if_indices = drv->default_if_indices;
2829                 else
2830                         drv->if_indices = old;
2831                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
2832                            "interfaces");
2833                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
2834                 return;
2835         }
2836         drv->if_indices[drv->num_if_indices] = ifidx;
2837         drv->num_if_indices++;
2838 }
2839
2840
2841 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
2842 {
2843         int i;
2844
2845         for (i = 0; i < drv->num_if_indices; i++) {
2846                 if (drv->if_indices[i] == ifidx) {
2847                         drv->if_indices[i] = 0;
2848                         break;
2849                 }
2850         }
2851 }
2852
2853
2854 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
2855 {
2856         int i;
2857
2858         for (i = 0; i < drv->num_if_indices; i++)
2859                 if (drv->if_indices[i] == ifidx)
2860                         return 1;
2861
2862         return 0;
2863 }
2864
2865
2866 static int hostapd_set_iface_flags(struct wpa_driver_nl80211_data *drv,
2867                                    const char *ifname, int dev_up)
2868 {
2869         struct ifreq ifr;
2870
2871         if (drv->ioctl_sock < 0)
2872                 return -1;
2873
2874         memset(&ifr, 0, sizeof(ifr));
2875         os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
2876
2877         if (ioctl(drv->ioctl_sock, SIOCGIFFLAGS, &ifr) != 0) {
2878                 perror("ioctl[SIOCGIFFLAGS]");
2879                 wpa_printf(MSG_DEBUG, "Could not read interface flags (%s)",
2880                            drv->ifname);
2881                 return -1;
2882         }
2883
2884         if (dev_up)
2885                 ifr.ifr_flags |= IFF_UP;
2886         else
2887                 ifr.ifr_flags &= ~IFF_UP;
2888
2889         if (ioctl(drv->ioctl_sock, SIOCSIFFLAGS, &ifr) != 0) {
2890                 perror("ioctl[SIOCSIFFLAGS]");
2891                 return -1;
2892         }
2893
2894         return 0;
2895 }
2896
2897
2898 static int i802_set_key(const char *iface, void *priv, wpa_alg alg,
2899                         const u8 *addr, int key_idx, int set_tx, const u8 *seq,
2900                         size_t seq_len, const u8 *key, size_t key_len)
2901 {
2902         struct wpa_driver_nl80211_data *drv = priv;
2903         return nl_set_encr(if_nametoindex(iface), drv, alg, addr, key_idx,
2904                            set_tx, seq, seq_len, key, key_len);
2905 }
2906
2907
2908 static inline int min_int(int a, int b)
2909 {
2910         if (a < b)
2911                 return a;
2912         return b;
2913 }
2914
2915
2916 static int get_key_handler(struct nl_msg *msg, void *arg)
2917 {
2918         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2919         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2920
2921         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2922                   genlmsg_attrlen(gnlh, 0), NULL);
2923
2924         /*
2925          * TODO: validate the key index and mac address!
2926          * Otherwise, there's a race condition as soon as
2927          * the kernel starts sending key notifications.
2928          */
2929
2930         if (tb[NL80211_ATTR_KEY_SEQ])
2931                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
2932                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
2933         return NL_SKIP;
2934 }
2935
2936
2937 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
2938                            int idx, u8 *seq)
2939 {
2940         struct wpa_driver_nl80211_data *drv = priv;
2941         struct nl_msg *msg;
2942
2943         msg = nlmsg_alloc();
2944         if (!msg)
2945                 return -ENOMEM;
2946
2947         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2948                     0, NL80211_CMD_GET_KEY, 0);
2949
2950         if (addr)
2951                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2952         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
2953         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
2954
2955         memset(seq, 0, 6);
2956
2957         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
2958  nla_put_failure:
2959         return -ENOBUFS;
2960 }
2961
2962
2963 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
2964                               int mode)
2965 {
2966         struct wpa_driver_nl80211_data *drv = priv;
2967         struct nl_msg *msg;
2968         u8 rates[NL80211_MAX_SUPP_RATES];
2969         u8 rates_len = 0;
2970         int i;
2971
2972         msg = nlmsg_alloc();
2973         if (!msg)
2974                 return -ENOMEM;
2975
2976         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2977                     NL80211_CMD_SET_BSS, 0);
2978
2979         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
2980                 rates[rates_len++] = basic_rates[i] / 5;
2981
2982         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
2983
2984         /* TODO: multi-BSS support */
2985         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
2986
2987         return send_and_recv_msgs(drv, msg, NULL, NULL);
2988  nla_put_failure:
2989         return -ENOBUFS;
2990 }
2991
2992
2993 static int i802_send_frame(void *priv, const void *data, size_t len,
2994                            int encrypt, int flags)
2995 {
2996         __u8 rtap_hdr[] = {
2997                 0x00, 0x00, /* radiotap version */
2998                 0x0e, 0x00, /* radiotap length */
2999                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
3000                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
3001                 0x00,       /* padding */
3002                 0x00, 0x00, /* RX and TX flags to indicate that */
3003                 0x00, 0x00, /* this is the injected frame directly */
3004         };
3005         struct wpa_driver_nl80211_data *drv = priv;
3006         struct iovec iov[2] = {
3007                 {
3008                         .iov_base = &rtap_hdr,
3009                         .iov_len = sizeof(rtap_hdr),
3010                 },
3011                 {
3012                         .iov_base = (void*)data,
3013                         .iov_len = len,
3014                 }
3015         };
3016         struct msghdr msg = {
3017                 .msg_name = NULL,
3018                 .msg_namelen = 0,
3019                 .msg_iov = iov,
3020                 .msg_iovlen = 2,
3021                 .msg_control = NULL,
3022                 .msg_controllen = 0,
3023                 .msg_flags = 0,
3024         };
3025
3026         if (encrypt)
3027                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
3028
3029         return sendmsg(drv->monitor_sock, &msg, flags);
3030 }
3031
3032 static int i802_send_mgmt_frame(void *priv, const void *data, size_t len,
3033                                 int flags)
3034 {
3035         struct ieee80211_mgmt *mgmt;
3036         int do_not_encrypt = 0;
3037         u16 fc;
3038
3039         mgmt = (struct ieee80211_mgmt *) data;
3040         fc = le_to_host16(mgmt->frame_control);
3041
3042         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3043             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
3044                 /*
3045                  * Only one of the authentication frame types is encrypted.
3046                  * In order for static WEP encryption to work properly (i.e.,
3047                  * to not encrypt the frame), we need to tell mac80211 about
3048                  * the frames that must not be encrypted.
3049                  */
3050                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
3051                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
3052                 if (auth_alg == WLAN_AUTH_OPEN ||
3053                     (auth_alg == WLAN_AUTH_SHARED_KEY && auth_trans != 3))
3054                         do_not_encrypt = 1;
3055         }
3056
3057         return i802_send_frame(priv, data, len, !do_not_encrypt, flags);
3058 }
3059
3060 /* Set kernel driver on given frequency (MHz) */
3061 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
3062 {
3063         struct wpa_driver_nl80211_data *drv = priv;
3064         struct nl_msg *msg;
3065
3066         msg = nlmsg_alloc();
3067         if (!msg)
3068                 return -1;
3069
3070         drv->last_freq = freq->freq;
3071         drv->last_freq_ht = freq->ht_enabled;
3072
3073         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3074                     NL80211_CMD_SET_WIPHY, 0);
3075
3076         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3077         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq->freq);
3078         if (freq->ht_enabled) {
3079                 switch (freq->sec_channel_offset) {
3080                 case -1:
3081                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3082                                     NL80211_CHAN_HT40MINUS);
3083                         break;
3084                 case 1:
3085                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3086                                     NL80211_CHAN_HT40PLUS);
3087                         break;
3088                 default:
3089                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3090                                     NL80211_CHAN_HT20);
3091                         break;
3092                 }
3093         }
3094
3095         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3096                 return 0;
3097  nla_put_failure:
3098         return -1;
3099 }
3100
3101
3102 static int i802_set_rts(void *priv, int rts)
3103 {
3104         struct wpa_driver_nl80211_data *drv = priv;
3105         struct iwreq iwr;
3106
3107         memset(&iwr, 0, sizeof(iwr));
3108         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
3109         iwr.u.rts.value = rts;
3110         iwr.u.rts.fixed = 1;
3111
3112         if (ioctl(drv->ioctl_sock, SIOCSIWRTS, &iwr) < 0) {
3113                 perror("ioctl[SIOCSIWRTS]");
3114                 return -1;
3115         }
3116
3117         return 0;
3118 }
3119
3120
3121 static int i802_set_frag(void *priv, int frag)
3122 {
3123         struct wpa_driver_nl80211_data *drv = priv;
3124         struct iwreq iwr;
3125
3126         memset(&iwr, 0, sizeof(iwr));
3127         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
3128         iwr.u.frag.value = frag;
3129         iwr.u.frag.fixed = 1;
3130
3131         if (ioctl(drv->ioctl_sock, SIOCSIWFRAG, &iwr) < 0) {
3132                 perror("ioctl[SIOCSIWFRAG]");
3133                 return -1;
3134         }
3135
3136         return 0;
3137 }
3138
3139
3140 static int i802_set_retry(void *priv, int short_retry, int long_retry)
3141 {
3142         struct wpa_driver_nl80211_data *drv = priv;
3143         struct iwreq iwr;
3144
3145         memset(&iwr, 0, sizeof(iwr));
3146         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
3147
3148         iwr.u.retry.value = short_retry;
3149         iwr.u.retry.flags = IW_RETRY_LIMIT | IW_RETRY_MIN;
3150         if (ioctl(drv->ioctl_sock, SIOCSIWRETRY, &iwr) < 0) {
3151                 perror("ioctl[SIOCSIWRETRY(short)]");
3152                 return -1;
3153         }
3154
3155         iwr.u.retry.value = long_retry;
3156         iwr.u.retry.flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
3157         if (ioctl(drv->ioctl_sock, SIOCSIWRETRY, &iwr) < 0) {
3158                 perror("ioctl[SIOCSIWRETRY(long)]");
3159                 return -1;
3160         }
3161
3162         return 0;
3163 }
3164
3165
3166 static int i802_flush(void *priv)
3167 {
3168         struct wpa_driver_nl80211_data *drv = priv;
3169         struct nl_msg *msg;
3170
3171         msg = nlmsg_alloc();
3172         if (!msg)
3173                 return -1;
3174
3175         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3176                     0, NL80211_CMD_DEL_STATION, 0);
3177
3178         /*
3179          * XXX: FIX! this needs to flush all VLANs too
3180          */
3181         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3182                     if_nametoindex(drv->ifname));
3183
3184         return send_and_recv_msgs(drv, msg, NULL, NULL);
3185  nla_put_failure:
3186         return -ENOBUFS;
3187 }
3188
3189
3190 static int get_sta_handler(struct nl_msg *msg, void *arg)
3191 {
3192         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3193         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3194         struct hostap_sta_driver_data *data = arg;
3195         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
3196         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
3197                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
3198                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
3199                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
3200                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
3201                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
3202         };
3203
3204         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3205                   genlmsg_attrlen(gnlh, 0), NULL);
3206
3207         /*
3208          * TODO: validate the interface and mac address!
3209          * Otherwise, there's a race condition as soon as
3210          * the kernel starts sending station notifications.
3211          */
3212
3213         if (!tb[NL80211_ATTR_STA_INFO]) {
3214                 wpa_printf(MSG_DEBUG, "sta stats missing!");
3215                 return NL_SKIP;
3216         }
3217         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
3218                              tb[NL80211_ATTR_STA_INFO],
3219                              stats_policy)) {
3220                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
3221                 return NL_SKIP;
3222         }
3223
3224         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
3225                 data->inactive_msec =
3226                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
3227         if (stats[NL80211_STA_INFO_RX_BYTES])
3228                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
3229         if (stats[NL80211_STA_INFO_TX_BYTES])
3230                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
3231         if (stats[NL80211_STA_INFO_RX_PACKETS])
3232                 data->rx_packets =
3233                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
3234         if (stats[NL80211_STA_INFO_TX_PACKETS])
3235                 data->tx_packets =
3236                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
3237
3238         return NL_SKIP;
3239 }
3240
3241 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
3242                               const u8 *addr)
3243 {
3244         struct wpa_driver_nl80211_data *drv = priv;
3245         struct nl_msg *msg;
3246
3247         os_memset(data, 0, sizeof(*data));
3248         msg = nlmsg_alloc();
3249         if (!msg)
3250                 return -ENOMEM;
3251
3252         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3253                     0, NL80211_CMD_GET_STATION, 0);
3254
3255         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3256         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3257
3258         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
3259  nla_put_failure:
3260         return -ENOBUFS;
3261 }
3262
3263
3264 static int i802_send_eapol(void *priv, const u8 *addr, const u8 *data,
3265                            size_t data_len, int encrypt, const u8 *own_addr)
3266 {
3267         struct wpa_driver_nl80211_data *drv = priv;
3268         struct ieee80211_hdr *hdr;
3269         size_t len;
3270         u8 *pos;
3271         int res;
3272 #if 0 /* FIX */
3273         int qos = sta->flags & WLAN_STA_WME;
3274 #else
3275         int qos = 0;
3276 #endif
3277
3278         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
3279                 data_len;
3280         hdr = os_zalloc(len);
3281         if (hdr == NULL) {
3282                 printf("malloc() failed for i802_send_data(len=%lu)\n",
3283                        (unsigned long) len);
3284                 return -1;
3285         }
3286
3287         hdr->frame_control =
3288                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
3289         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
3290         if (encrypt)
3291                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
3292 #if 0 /* To be enabled if qos determination is added above */
3293         if (qos) {
3294                 hdr->frame_control |=
3295                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
3296         }
3297 #endif
3298
3299         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
3300         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
3301         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
3302         pos = (u8 *) (hdr + 1);
3303
3304 #if 0 /* To be enabled if qos determination is added above */
3305         if (qos) {
3306                 /* add an empty QoS header if needed */
3307                 pos[0] = 0;
3308                 pos[1] = 0;
3309                 pos += 2;
3310         }
3311 #endif
3312
3313         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
3314         pos += sizeof(rfc1042_header);
3315         WPA_PUT_BE16(pos, ETH_P_PAE);
3316         pos += 2;
3317         memcpy(pos, data, data_len);
3318
3319         res = i802_send_frame(drv, (u8 *) hdr, len, encrypt, 0);
3320         free(hdr);
3321
3322         if (res < 0) {
3323                 perror("i802_send_eapol: send");
3324                 printf("i802_send_eapol - packet len: %lu - failed\n",
3325                        (unsigned long) len);
3326         }
3327
3328         return res;
3329 }
3330
3331
3332 static int i802_sta_add(const char *ifname, void *priv,
3333                         struct hostapd_sta_add_params *params)
3334 {
3335         struct wpa_driver_nl80211_data *drv = priv;
3336         struct nl_msg *msg;
3337         int ret = -ENOBUFS;
3338
3339         msg = nlmsg_alloc();
3340         if (!msg)
3341                 return -ENOMEM;
3342
3343         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3344                     0, NL80211_CMD_NEW_STATION, 0);
3345
3346         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3347                     if_nametoindex(drv->ifname));
3348         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
3349         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
3350         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
3351                 params->supp_rates);
3352         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
3353                     params->listen_interval);
3354
3355 #ifdef CONFIG_IEEE80211N
3356         if (params->ht_capabilities) {
3357                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
3358                         params->ht_capabilities->length,
3359                         &params->ht_capabilities->data);
3360         }
3361 #endif /* CONFIG_IEEE80211N */
3362
3363         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3364         if (ret)
3365                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
3366                            "result: %d (%s)", ret, strerror(-ret));
3367         if (ret == -EEXIST)
3368                 ret = 0;
3369  nla_put_failure:
3370         return ret;
3371 }
3372
3373
3374 static int i802_sta_remove(void *priv, const u8 *addr)
3375 {
3376         struct wpa_driver_nl80211_data *drv = priv;
3377         struct nl_msg *msg;
3378         int ret;
3379
3380         msg = nlmsg_alloc();
3381         if (!msg)
3382                 return -ENOMEM;
3383
3384         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3385                     0, NL80211_CMD_DEL_STATION, 0);
3386
3387         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3388                     if_nametoindex(drv->ifname));
3389         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3390
3391         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3392         if (ret == -ENOENT)
3393                 return 0;
3394         return ret;
3395  nla_put_failure:
3396         return -ENOBUFS;
3397 }
3398
3399
3400 static int i802_sta_set_flags(void *priv, const u8 *addr,
3401                               int total_flags, int flags_or, int flags_and)
3402 {
3403         struct wpa_driver_nl80211_data *drv = priv;
3404         struct nl_msg *msg, *flags = NULL;
3405
3406         msg = nlmsg_alloc();
3407         if (!msg)
3408                 return -ENOMEM;
3409
3410         flags = nlmsg_alloc();
3411         if (!flags) {
3412                 nlmsg_free(msg);
3413                 return -ENOMEM;
3414         }
3415
3416         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3417                     0, NL80211_CMD_SET_STATION, 0);
3418
3419         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3420                     if_nametoindex(drv->ifname));
3421         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3422
3423         if (total_flags & WLAN_STA_AUTHORIZED)
3424                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
3425
3426         if (total_flags & WLAN_STA_WMM)
3427                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
3428
3429         if (total_flags & WLAN_STA_SHORT_PREAMBLE)
3430                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
3431
3432         if (total_flags & WLAN_STA_MFP)
3433                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
3434
3435         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
3436                 goto nla_put_failure;
3437
3438         nlmsg_free(flags);
3439
3440         return send_and_recv_msgs(drv, msg, NULL, NULL);
3441  nla_put_failure:
3442         nlmsg_free(flags);
3443         return -ENOBUFS;
3444 }
3445
3446
3447 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
3448                                     int cw_min, int cw_max, int burst_time)
3449 {
3450         struct wpa_driver_nl80211_data *drv = priv;
3451         struct nl_msg *msg;
3452         struct nlattr *txq, *params;
3453
3454         msg = nlmsg_alloc();
3455         if (!msg)
3456                 return -1;
3457
3458         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3459                     0, NL80211_CMD_SET_WIPHY, 0);
3460
3461         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3462
3463         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
3464         if (!txq)
3465                 goto nla_put_failure;
3466
3467         /* We are only sending parameters for a single TXQ at a time */
3468         params = nla_nest_start(msg, 1);
3469         if (!params)
3470                 goto nla_put_failure;
3471
3472         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, queue);
3473         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
3474          * 32 usec, so need to convert the value here. */
3475         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
3476         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
3477         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
3478         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
3479
3480         nla_nest_end(msg, params);
3481
3482         nla_nest_end(msg, txq);
3483
3484         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3485                 return 0;
3486  nla_put_failure:
3487         return -1;
3488 }
3489
3490
3491 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv, int ifidx)
3492 {
3493         struct nl_msg *msg;
3494
3495         /* stop listening for EAPOL on this interface */
3496         del_ifidx(drv, ifidx);
3497
3498         msg = nlmsg_alloc();
3499         if (!msg)
3500                 goto nla_put_failure;
3501
3502         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3503                     0, NL80211_CMD_DEL_INTERFACE, 0);
3504         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
3505
3506         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3507                 return;
3508  nla_put_failure:
3509         printf("Failed to remove interface.\n");
3510 }
3511
3512
3513 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
3514                                 const char *ifname,
3515                                 enum nl80211_iftype iftype,
3516                                 const u8 *addr)
3517 {
3518         struct nl_msg *msg, *flags = NULL;
3519         int ifidx;
3520         struct ifreq ifreq;
3521         struct iwreq iwr;
3522         int ret = -ENOBUFS;
3523
3524         msg = nlmsg_alloc();
3525         if (!msg)
3526                 return -1;
3527
3528         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3529                     0, NL80211_CMD_NEW_INTERFACE, 0);
3530         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3531         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
3532         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
3533
3534         if (iftype == NL80211_IFTYPE_MONITOR) {
3535                 int err;
3536
3537                 flags = nlmsg_alloc();
3538                 if (!flags)
3539                         goto nla_put_failure;
3540
3541                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
3542
3543                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
3544
3545                 nlmsg_free(flags);
3546
3547                 if (err)
3548                         goto nla_put_failure;
3549         }
3550
3551         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3552         if (ret) {
3553  nla_put_failure:
3554                 printf("Failed to create interface %s.\n", ifname);
3555                 return ret;
3556         }
3557
3558         ifidx = if_nametoindex(ifname);
3559
3560         if (ifidx <= 0)
3561                 return -1;
3562
3563         /* start listening for EAPOL on this interface */
3564         add_ifidx(drv, ifidx);
3565
3566         if (addr) {
3567                 switch (iftype) {
3568                 case NL80211_IFTYPE_AP:
3569                         os_strlcpy(ifreq.ifr_name, ifname, IFNAMSIZ);
3570                         memcpy(ifreq.ifr_hwaddr.sa_data, addr, ETH_ALEN);
3571                         ifreq.ifr_hwaddr.sa_family = ARPHRD_ETHER;
3572
3573                         if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifreq)) {
3574                                 nl80211_remove_iface(drv, ifidx);
3575                                 return -1;
3576                         }
3577                         break;
3578                 case NL80211_IFTYPE_WDS:
3579                         memset(&iwr, 0, sizeof(iwr));
3580                         os_strlcpy(iwr.ifr_name, ifname, IFNAMSIZ);
3581                         iwr.u.addr.sa_family = ARPHRD_ETHER;
3582                         memcpy(iwr.u.addr.sa_data, addr, ETH_ALEN);
3583                         if (ioctl(drv->ioctl_sock, SIOCSIWAP, &iwr))
3584                                 return -1;
3585                         break;
3586                 default:
3587                         /* nothing */
3588                         break;
3589                 }
3590         }
3591
3592         return ifidx;
3593 }
3594
3595
3596 static int i802_bss_add(void *priv, const char *ifname, const u8 *bssid)
3597 {
3598         struct wpa_driver_nl80211_data *drv = priv;
3599         int ifidx;
3600         struct i802_bss *bss;
3601
3602         bss = os_zalloc(sizeof(*bss));
3603         if (bss == NULL)
3604                 return -1;
3605         os_strlcpy(bss->ifname, ifname, IFNAMSIZ);
3606
3607         ifidx = nl80211_create_iface(priv, ifname, NL80211_IFTYPE_AP, bssid);
3608         if (ifidx < 0) {
3609                 os_free(bss);
3610                 return -1;
3611         }
3612         if (hostapd_set_iface_flags(priv, ifname, 1)) {
3613                 nl80211_remove_iface(priv, ifidx);
3614                 os_free(bss);
3615                 return -1;
3616         }
3617         bss->next = drv->bss.next;
3618         drv->bss.next = bss;
3619         return 0;
3620 }
3621
3622
3623 static int i802_bss_remove(void *priv, const char *ifname)
3624 {
3625         struct wpa_driver_nl80211_data *drv = priv;
3626         struct i802_bss *bss, *prev;
3627         nl80211_remove_iface(priv, if_nametoindex(ifname));
3628         prev = &drv->bss;
3629         bss = drv->bss.next;
3630         while (bss) {
3631                 if (os_strncmp(ifname, bss->ifname, IFNAMSIZ) == 0) {
3632                         prev->next = bss->next;
3633                         os_free(bss);
3634                         break;
3635                 }
3636                 prev = bss;
3637                 bss = bss->next;
3638         }
3639         return 0;
3640 }
3641
3642
3643 static int i802_set_beacon(const char *iface, void *priv,
3644                            const u8 *head, size_t head_len,
3645                            const u8 *tail, size_t tail_len, int dtim_period)
3646 {
3647         struct wpa_driver_nl80211_data *drv = priv;
3648         struct nl_msg *msg;
3649         u8 cmd = NL80211_CMD_NEW_BEACON;
3650         int ret;
3651         struct i802_bss *bss;
3652
3653         bss = get_bss(drv, iface);
3654         if (bss == NULL)
3655                 return -ENOENT;
3656
3657         msg = nlmsg_alloc();
3658         if (!msg)
3659                 return -ENOMEM;
3660
3661         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (iface=%s beacon_set=%d)",
3662                    iface, bss->beacon_set);
3663         if (bss->beacon_set)
3664                 cmd = NL80211_CMD_SET_BEACON;
3665
3666         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3667                     0, cmd, 0);
3668         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
3669         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
3670         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
3671         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, drv->beacon_int);
3672         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
3673
3674         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3675         if (!ret)
3676                 bss->beacon_set = 1;
3677         return ret;
3678  nla_put_failure:
3679         return -ENOBUFS;
3680 }
3681
3682
3683 static int i802_del_beacon(struct wpa_driver_nl80211_data *drv)
3684 {
3685         struct nl_msg *msg;
3686
3687         msg = nlmsg_alloc();
3688         if (!msg)
3689                 return -ENOMEM;
3690
3691         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3692                     0, NL80211_CMD_DEL_BEACON, 0);
3693         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3694
3695         return send_and_recv_msgs(drv, msg, NULL, NULL);
3696  nla_put_failure:
3697         return -ENOBUFS;
3698 }
3699
3700
3701 static int i802_set_beacon_int(void *priv, int value)
3702 {
3703         struct wpa_driver_nl80211_data *drv = priv;
3704         struct nl_msg *msg;
3705
3706         drv->beacon_int = value;
3707
3708         if (!drv->bss.beacon_set)
3709                 return 0;
3710
3711         msg = nlmsg_alloc();
3712         if (!msg)
3713                 return -ENOMEM;
3714
3715         wpa_printf(MSG_DEBUG, "nl80211: Set beacon interval %d "
3716                    "(beacon_set=%d)", value, drv->bss.beacon_set);
3717         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3718                     0, NL80211_CMD_SET_BEACON, 0);
3719         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3720
3721         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, value);
3722
3723         return send_and_recv_msgs(drv, msg, NULL, NULL);
3724  nla_put_failure:
3725         return -ENOBUFS;
3726 }
3727
3728
3729 static int i802_set_bss(void *priv, int cts, int preamble, int slot)
3730 {
3731         struct wpa_driver_nl80211_data *drv = priv;
3732         struct nl_msg *msg;
3733
3734         msg = nlmsg_alloc();
3735         if (!msg)
3736                 return -ENOMEM;
3737
3738         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3739                     NL80211_CMD_SET_BSS, 0);
3740
3741         if (cts >= 0)
3742                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
3743         if (preamble >= 0)
3744                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
3745         if (slot >= 0)
3746                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
3747
3748         /* TODO: multi-BSS support */
3749         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3750
3751         return send_and_recv_msgs(drv, msg, NULL, NULL);
3752  nla_put_failure:
3753         return -ENOBUFS;
3754 }
3755
3756
3757 static int i802_set_cts_protect(void *priv, int value)
3758 {
3759         return i802_set_bss(priv, value, -1, -1);
3760 }
3761
3762
3763 static int i802_set_preamble(void *priv, int value)
3764 {
3765         return i802_set_bss(priv, -1, value, -1);
3766 }
3767
3768
3769 static int i802_set_short_slot_time(void *priv, int value)
3770 {
3771         return i802_set_bss(priv, -1, -1, value);
3772 }
3773
3774
3775 static enum nl80211_iftype i802_if_type(enum hostapd_driver_if_type type)
3776 {
3777         switch (type) {
3778         case HOSTAPD_IF_VLAN:
3779                 return NL80211_IFTYPE_AP_VLAN;
3780         case HOSTAPD_IF_WDS:
3781                 return NL80211_IFTYPE_WDS;
3782         }
3783         return -1;
3784 }
3785
3786
3787 static int i802_if_add(const char *iface, void *priv,
3788                        enum hostapd_driver_if_type type, char *ifname,
3789                        const u8 *addr)
3790 {
3791         if (nl80211_create_iface(priv, ifname, i802_if_type(type), addr) < 0)
3792                 return -1;
3793         return 0;
3794 }
3795
3796
3797 static int i802_if_update(void *priv, enum hostapd_driver_if_type type,
3798                           char *ifname, const u8 *addr)
3799 {
3800         /* unused at the moment */
3801         return -1;
3802 }
3803
3804
3805 static int i802_if_remove(void *priv, enum hostapd_driver_if_type type,
3806                           const char *ifname, const u8 *addr)
3807 {
3808         nl80211_remove_iface(priv, if_nametoindex(ifname));
3809         return 0;
3810 }
3811
3812
3813 static int i802_set_sta_vlan(void *priv, const u8 *addr,
3814                              const char *ifname, int vlan_id)
3815 {
3816         struct wpa_driver_nl80211_data *drv = priv;
3817         struct nl_msg *msg;
3818
3819         msg = nlmsg_alloc();
3820         if (!msg)
3821                 return -ENOMEM;
3822
3823         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3824                     0, NL80211_CMD_SET_STATION, 0);
3825
3826         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3827                     if_nametoindex(drv->ifname));
3828         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3829         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3830                     if_nametoindex(ifname));
3831
3832         return send_and_recv_msgs(drv, msg, NULL, NULL);
3833  nla_put_failure:
3834         return -ENOBUFS;
3835 }
3836
3837
3838 static int i802_set_country(void *priv, const char *country)
3839 {
3840         struct wpa_driver_nl80211_data *drv = priv;
3841         struct nl_msg *msg;
3842         char alpha2[3];
3843
3844         msg = nlmsg_alloc();
3845         if (!msg)
3846                 return -ENOMEM;
3847
3848         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3849                     0, NL80211_CMD_REQ_SET_REG, 0);
3850
3851         alpha2[0] = country[0];
3852         alpha2[1] = country[1];
3853         alpha2[2] = '\0';
3854         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
3855
3856         return send_and_recv_msgs(drv, msg, NULL, NULL);
3857  nla_put_failure:
3858         return -ENOBUFS;
3859 }
3860
3861
3862 static void handle_tx_callback(struct hostapd_data *hapd, u8 *buf, size_t len,
3863                                int ok)
3864 {
3865         struct ieee80211_hdr *hdr;
3866         u16 fc, type, stype;
3867
3868         hdr = (struct ieee80211_hdr *) buf;
3869         fc = le_to_host16(hdr->frame_control);
3870
3871         type = WLAN_FC_GET_TYPE(fc);
3872         stype = WLAN_FC_GET_STYPE(fc);
3873
3874         switch (type) {
3875         case WLAN_FC_TYPE_MGMT:
3876                 wpa_printf(MSG_DEBUG, "MGMT (TX callback) %s",
3877                            ok ? "ACK" : "fail");
3878                 hostapd_mgmt_tx_cb(hapd, buf, len, stype, ok);
3879                 break;
3880         case WLAN_FC_TYPE_CTRL:
3881                 wpa_printf(MSG_DEBUG, "CTRL (TX callback) %s",
3882                            ok ? "ACK" : "fail");
3883                 break;
3884         case WLAN_FC_TYPE_DATA:
3885                 hostapd_tx_status(hapd, hdr->addr1, buf, len, ok);
3886                 break;
3887         default:
3888                 printf("unknown TX callback frame type %d\n", type);
3889                 break;
3890         }
3891 }
3892
3893
3894 static void handle_frame(struct wpa_driver_nl80211_data *drv,
3895                          struct hostapd_iface *iface, u8 *buf, size_t len,
3896                          struct hostapd_frame_info *hfi,
3897                          enum ieee80211_msg_type msg_type)
3898 {
3899         struct ieee80211_hdr *hdr;
3900         u16 fc, type, stype;
3901         size_t data_len = len;
3902         struct hostapd_data *hapd = NULL;
3903         int broadcast_bssid = 0;
3904         size_t i;
3905         u8 *bssid;
3906
3907         /*
3908          * PS-Poll frames are 16 bytes. All other frames are
3909          * 24 bytes or longer.
3910          */
3911         if (len < 16)
3912                 return;
3913
3914         hdr = (struct ieee80211_hdr *) buf;
3915         fc = le_to_host16(hdr->frame_control);
3916
3917         type = WLAN_FC_GET_TYPE(fc);
3918         stype = WLAN_FC_GET_STYPE(fc);
3919
3920         switch (type) {
3921         case WLAN_FC_TYPE_DATA:
3922                 if (len < 24)
3923                         return;
3924                 switch (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) {
3925                 case WLAN_FC_TODS:
3926                         bssid = hdr->addr1;
3927                         break;
3928                 case WLAN_FC_FROMDS:
3929                         bssid = hdr->addr2;
3930                         break;
3931                 default:
3932                         /* discard */
3933                         return;
3934                 }
3935                 break;
3936         case WLAN_FC_TYPE_CTRL:
3937                 /* discard non-ps-poll frames */
3938                 if (stype != WLAN_FC_STYPE_PSPOLL)
3939                         return;
3940                 bssid = hdr->addr1;
3941                 break;
3942         case WLAN_FC_TYPE_MGMT:
3943                 bssid = hdr->addr3;
3944                 break;
3945         default:
3946                 /* discard */
3947                 return;
3948         }
3949
3950         /* find interface frame belongs to */
3951         for (i = 0; i < iface->num_bss; i++) {
3952                 if (memcmp(bssid, iface->bss[i]->own_addr, ETH_ALEN) == 0) {
3953                         hapd = iface->bss[i];
3954                         break;
3955                 }
3956         }
3957
3958         if (hapd == NULL) {
3959                 hapd = iface->bss[0];
3960
3961                 if (bssid[0] != 0xff || bssid[1] != 0xff ||
3962                     bssid[2] != 0xff || bssid[3] != 0xff ||
3963                     bssid[4] != 0xff || bssid[5] != 0xff) {
3964                         /*
3965                          * Unknown BSSID - drop frame if this is not from
3966                          * passive scanning or a beacon (at least ProbeReq
3967                          * frames to other APs may be allowed through RX
3968                          * filtering in the wlan hw/driver)
3969                          */
3970                         if ((type != WLAN_FC_TYPE_MGMT ||
3971                              stype != WLAN_FC_STYPE_BEACON))
3972                                 return;
3973                 } else
3974                         broadcast_bssid = 1;
3975         }
3976
3977         switch (msg_type) {
3978         case ieee80211_msg_normal:
3979                 /* continue processing */
3980                 break;
3981         case ieee80211_msg_tx_callback_ack:
3982                 handle_tx_callback(hapd, buf, data_len, 1);
3983                 return;
3984         case ieee80211_msg_tx_callback_fail:
3985                 handle_tx_callback(hapd, buf, data_len, 0);
3986                 return;
3987         }
3988
3989         switch (type) {
3990         case WLAN_FC_TYPE_MGMT:
3991                 if (stype != WLAN_FC_STYPE_BEACON &&
3992                     stype != WLAN_FC_STYPE_PROBE_REQ)
3993                         wpa_printf(MSG_MSGDUMP, "MGMT");
3994                 if (broadcast_bssid) {
3995                         for (i = 0; i < iface->num_bss; i++)
3996                                 hostapd_mgmt_rx(iface->bss[i], buf, data_len,
3997                                                 stype, hfi);
3998                 } else
3999                         hostapd_mgmt_rx(hapd, buf, data_len, stype, hfi);
4000                 break;
4001         case WLAN_FC_TYPE_CTRL:
4002                 /* can only get here with PS-Poll frames */
4003                 wpa_printf(MSG_DEBUG, "CTRL");
4004                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
4005                 break;
4006         case WLAN_FC_TYPE_DATA:
4007                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
4008                 break;
4009         }
4010 }
4011
4012
4013 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
4014 {
4015         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4016         struct sockaddr_ll lladdr;
4017         unsigned char buf[3000];
4018         int len;
4019         socklen_t fromlen = sizeof(lladdr);
4020
4021         len = recvfrom(sock, buf, sizeof(buf), 0,
4022                        (struct sockaddr *)&lladdr, &fromlen);
4023         if (len < 0) {
4024                 perror("recv");
4025                 return;
4026         }
4027
4028         if (have_ifidx(drv, lladdr.sll_ifindex)) {
4029                 struct hostapd_data *hapd;
4030                 hapd = hostapd_sta_get_bss(drv->hapd, lladdr.sll_addr);
4031                 if (!hapd)
4032                         return;
4033                 hostapd_eapol_receive(hapd, lladdr.sll_addr, buf, len);
4034         }
4035 }
4036
4037
4038 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
4039 {
4040         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4041         int len;
4042         unsigned char buf[3000];
4043         struct hostapd_data *hapd = drv->hapd;
4044         struct ieee80211_radiotap_iterator iter;
4045         int ret;
4046         struct hostapd_frame_info hfi;
4047         int injected = 0, failed = 0, msg_type, rxflags = 0;
4048
4049         len = recv(sock, buf, sizeof(buf), 0);
4050         if (len < 0) {
4051                 perror("recv");
4052                 return;
4053         }
4054
4055         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
4056                 printf("received invalid radiotap frame\n");
4057                 return;
4058         }
4059
4060         memset(&hfi, 0, sizeof(hfi));
4061
4062         while (1) {
4063                 ret = ieee80211_radiotap_iterator_next(&iter);
4064                 if (ret == -ENOENT)
4065                         break;
4066                 if (ret) {
4067                         printf("received invalid radiotap frame (%d)\n", ret);
4068                         return;
4069                 }
4070                 switch (iter.this_arg_index) {
4071                 case IEEE80211_RADIOTAP_FLAGS:
4072                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
4073                                 len -= 4;
4074                         break;
4075                 case IEEE80211_RADIOTAP_RX_FLAGS:
4076                         rxflags = 1;
4077                         break;
4078                 case IEEE80211_RADIOTAP_TX_FLAGS:
4079                         injected = 1;
4080                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
4081                                         IEEE80211_RADIOTAP_F_TX_FAIL;
4082                         break;
4083                 case IEEE80211_RADIOTAP_DATA_RETRIES:
4084                         break;
4085                 case IEEE80211_RADIOTAP_CHANNEL:
4086                         /* TODO convert from freq/flags to channel number
4087                         hfi.channel = XXX;
4088                         hfi.phytype = XXX;
4089                          */
4090                         break;
4091                 case IEEE80211_RADIOTAP_RATE:
4092                         hfi.datarate = *iter.this_arg * 5;
4093                         break;
4094                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
4095                         hfi.ssi_signal = *iter.this_arg;
4096                         break;
4097                 }
4098         }
4099
4100         if (rxflags && injected)
4101                 return;
4102
4103         if (!injected)
4104                 msg_type = ieee80211_msg_normal;
4105         else if (failed)
4106                 msg_type = ieee80211_msg_tx_callback_fail;
4107         else
4108                 msg_type = ieee80211_msg_tx_callback_ack;
4109
4110         handle_frame(drv, hapd->iface, buf + iter.max_length,
4111                      len - iter.max_length, &hfi, msg_type);
4112 }
4113
4114
4115 /*
4116  * we post-process the filter code later and rewrite
4117  * this to the offset to the last instruction
4118  */
4119 #define PASS    0xFF
4120 #define FAIL    0xFE
4121
4122 static struct sock_filter msock_filter_insns[] = {
4123         /*
4124          * do a little-endian load of the radiotap length field
4125          */
4126         /* load lower byte into A */
4127         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
4128         /* put it into X (== index register) */
4129         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4130         /* load upper byte into A */
4131         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
4132         /* left-shift it by 8 */
4133         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
4134         /* or with X */
4135         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
4136         /* put result into X */
4137         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4138
4139         /*
4140          * Allow management frames through, this also gives us those
4141          * management frames that we sent ourselves with status
4142          */
4143         /* load the lower byte of the IEEE 802.11 frame control field */
4144         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
4145         /* mask off frame type and version */
4146         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
4147         /* accept frame if it's both 0, fall through otherwise */
4148         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
4149
4150         /*
4151          * TODO: add a bit to radiotap RX flags that indicates
4152          * that the sending station is not associated, then
4153          * add a filter here that filters on our DA and that flag
4154          * to allow us to deauth frames to that bad station.
4155          *
4156          * Not a regression -- we didn't do it before either.
4157          */
4158
4159 #if 0
4160         /*
4161          * drop non-data frames, WDS frames
4162          */
4163         /* load the lower byte of the frame control field */
4164         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4165         /* mask off QoS bit */
4166         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
4167         /* drop non-data frames */
4168         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
4169         /* load the upper byte of the frame control field */
4170         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4171         /* mask off toDS/fromDS */
4172         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
4173         /* drop WDS frames */
4174         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, FAIL, 0),
4175 #endif
4176
4177         /*
4178          * add header length to index
4179          */
4180         /* load the lower byte of the frame control field */
4181         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4182         /* mask off QoS bit */
4183         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
4184         /* right shift it by 6 to give 0 or 2 */
4185         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
4186         /* add data frame header length */
4187         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
4188         /* add index, was start of 802.11 header */
4189         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
4190         /* move to index, now start of LL header */
4191         BPF_STMT(BPF_MISC | BPF_TAX, 0),
4192
4193         /*
4194          * Accept empty data frames, we use those for
4195          * polling activity.
4196          */
4197         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
4198         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
4199
4200         /*
4201          * Accept EAPOL frames
4202          */
4203         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
4204         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
4205         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
4206         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
4207
4208         /* keep these last two statements or change the code below */
4209         /* return 0 == "DROP" */
4210         BPF_STMT(BPF_RET | BPF_K, 0),
4211         /* return ~0 == "keep all" */
4212         BPF_STMT(BPF_RET | BPF_K, ~0),
4213 };
4214
4215 static struct sock_fprog msock_filter = {
4216         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
4217         .filter = msock_filter_insns,
4218 };
4219
4220
4221 static int add_monitor_filter(int s)
4222 {
4223         int idx;
4224
4225         /* rewrite all PASS/FAIL jump offsets */
4226         for (idx = 0; idx < msock_filter.len; idx++) {
4227                 struct sock_filter *insn = &msock_filter_insns[idx];
4228
4229                 if (BPF_CLASS(insn->code) == BPF_JMP) {
4230                         if (insn->code == (BPF_JMP|BPF_JA)) {
4231                                 if (insn->k == PASS)
4232                                         insn->k = msock_filter.len - idx - 2;
4233                                 else if (insn->k == FAIL)
4234                                         insn->k = msock_filter.len - idx - 3;
4235                         }
4236
4237                         if (insn->jt == PASS)
4238                                 insn->jt = msock_filter.len - idx - 2;
4239                         else if (insn->jt == FAIL)
4240                                 insn->jt = msock_filter.len - idx - 3;
4241
4242                         if (insn->jf == PASS)
4243                                 insn->jf = msock_filter.len - idx - 2;
4244                         else if (insn->jf == FAIL)
4245                                 insn->jf = msock_filter.len - idx - 3;
4246                 }
4247         }
4248
4249         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
4250                        &msock_filter, sizeof(msock_filter))) {
4251                 perror("SO_ATTACH_FILTER");
4252                 return -1;
4253         }
4254
4255         return 0;
4256 }
4257
4258
4259 static int nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
4260 {
4261         char buf[IFNAMSIZ];
4262         struct sockaddr_ll ll;
4263         int optval;
4264         socklen_t optlen;
4265
4266         snprintf(buf, IFNAMSIZ, "mon.%s", drv->ifname);
4267         buf[IFNAMSIZ - 1] = '\0';
4268
4269         drv->monitor_ifidx =
4270                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL);
4271
4272         if (drv->monitor_ifidx < 0)
4273                 return -1;
4274
4275         if (hostapd_set_iface_flags(drv, buf, 1))
4276                 goto error;
4277
4278         memset(&ll, 0, sizeof(ll));
4279         ll.sll_family = AF_PACKET;
4280         ll.sll_ifindex = drv->monitor_ifidx;
4281         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
4282         if (drv->monitor_sock < 0) {
4283                 perror("socket[PF_PACKET,SOCK_RAW]");
4284                 goto error;
4285         }
4286
4287         if (add_monitor_filter(drv->monitor_sock)) {
4288                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
4289                            "interface; do filtering in user space");
4290                 /* This works, but will cost in performance. */
4291         }
4292
4293         if (bind(drv->monitor_sock, (struct sockaddr *) &ll,
4294                  sizeof(ll)) < 0) {
4295                 perror("monitor socket bind");
4296                 goto error;
4297         }
4298
4299         optlen = sizeof(optval);
4300         optval = 20;
4301         if (setsockopt
4302             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
4303                 perror("Failed to set socket priority");
4304                 goto error;
4305         }
4306
4307         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
4308                                      drv, NULL)) {
4309                 printf("Could not register monitor read socket\n");
4310                 goto error;
4311         }
4312
4313         return 0;
4314  error:
4315         nl80211_remove_iface(drv, drv->monitor_ifidx);
4316         return -1;
4317 }
4318
4319
4320 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv, const char *ifname,
4321                             int mode)
4322 {
4323         struct nl_msg *msg;
4324         int ret = -ENOBUFS;
4325
4326         msg = nlmsg_alloc();
4327         if (!msg)
4328                 return -ENOMEM;
4329
4330         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4331                     0, NL80211_CMD_SET_INTERFACE, 0);
4332         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4333                     if_nametoindex(ifname));
4334         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
4335
4336         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4337         if (!ret)
4338                 return 0;
4339  nla_put_failure:
4340         wpa_printf(MSG_ERROR, "Failed to set interface %s to master "
4341                    "mode.", ifname);
4342         return ret;
4343 }
4344
4345
4346 #ifdef CONFIG_IEEE80211N
4347 static void i802_add_neighbor(struct wpa_driver_nl80211_data *drv, u8 *bssid,
4348                               int freq, u8 *ie, size_t ie_len)
4349 {
4350         struct ieee802_11_elems elems;
4351         int ht, pri_chan = 0, sec_chan = 0;
4352         struct ieee80211_ht_operation *oper;
4353         struct hostapd_neighbor_bss *nnei;
4354
4355         ieee802_11_parse_elems(ie, ie_len, &elems, 0);
4356         ht = elems.ht_capabilities || elems.ht_operation;
4357         if (elems.ht_operation && elems.ht_operation_len >= sizeof(*oper)) {
4358                 oper = (struct ieee80211_ht_operation *) elems.ht_operation;
4359                 pri_chan = oper->control_chan;
4360                 if (oper->ht_param & HT_INFO_HT_PARAM_REC_TRANS_CHNL_WIDTH) {
4361                         if (oper->ht_param &
4362                             HT_INFO_HT_PARAM_SECONDARY_CHNL_ABOVE)
4363                                 sec_chan = pri_chan + 4;
4364                         else if (oper->ht_param &
4365                             HT_INFO_HT_PARAM_SECONDARY_CHNL_BELOW)
4366                                 sec_chan = pri_chan - 4;
4367                 }
4368         }
4369
4370         wpa_printf(MSG_DEBUG, "nl80211: Neighboring BSS - bssid=" MACSTR
4371                    " freq=%d MHz HT=%d pri_chan=%d sec_chan=%d",
4372                    MAC2STR(bssid), freq, ht, pri_chan, sec_chan);
4373
4374         nnei = os_realloc(drv->neighbors, (drv->num_neighbors + 1) *
4375                           sizeof(struct hostapd_neighbor_bss));
4376         if (nnei == NULL)
4377                 return;
4378         drv->neighbors = nnei;
4379         nnei = &nnei[drv->num_neighbors];
4380         os_memcpy(nnei->bssid, bssid, ETH_ALEN);
4381         nnei->freq = freq;
4382         nnei->ht = !!ht;
4383         nnei->pri_chan = pri_chan;
4384         nnei->sec_chan = sec_chan;
4385         drv->num_neighbors++;
4386 }
4387
4388
4389 static int i802_get_scan_freq(struct iw_event *iwe, int *freq)
4390 {
4391         int divi = 1000000, i;
4392
4393         if (iwe->u.freq.e == 0) {
4394                 /*
4395                  * Some drivers do not report frequency, but a channel.
4396                  * Try to map this to frequency by assuming they are using
4397                  * IEEE 802.11b/g.  But don't overwrite a previously parsed
4398                  * frequency if the driver sends both frequency and channel,
4399                  * since the driver may be sending an A-band channel that we
4400                  * don't handle here.
4401                  */
4402
4403                 if (*freq)
4404                         return 0;
4405
4406                 if (iwe->u.freq.m >= 1 && iwe->u.freq.m <= 13) {
4407                         *freq = 2407 + 5 * iwe->u.freq.m;
4408                         return 0;
4409                 } else if (iwe->u.freq.m == 14) {
4410                         *freq = 2484;
4411                         return 0;
4412                 }
4413         }
4414
4415         if (iwe->u.freq.e > 6) {
4416                 wpa_printf(MSG_DEBUG, "Invalid freq in scan results: "
4417                            "m=%d e=%d", iwe->u.freq.m, iwe->u.freq.e);
4418                 return -1;
4419         }
4420
4421         for (i = 0; i < iwe->u.freq.e; i++)
4422                 divi /= 10;
4423         *freq = iwe->u.freq.m / divi;
4424         return 0;
4425 }
4426
4427
4428 static int i802_parse_scan(struct wpa_driver_nl80211_data *drv, u8 *res_buf,
4429                            size_t len)
4430 {
4431         size_t ap_num = 0;
4432         int first;
4433         struct iw_event iwe_buf, *iwe = &iwe_buf;
4434         char *pos, *end, *custom;
4435         u8 bssid[ETH_ALEN];
4436         int freq = 0;
4437         u8 *ie = NULL;
4438         size_t ie_len = 0;
4439
4440         ap_num = 0;
4441         first = 1;
4442
4443         pos = (char *) res_buf;
4444         end = (char *) res_buf + len;
4445
4446         while (pos + IW_EV_LCP_LEN <= end) {
4447                 /* Event data may be unaligned, so make a local, aligned copy
4448                  * before processing. */
4449                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
4450                 if (iwe->len <= IW_EV_LCP_LEN)
4451                         break;
4452
4453                 custom = pos + IW_EV_POINT_LEN;
4454                 if (iwe->cmd == IWEVGENIE) {
4455                         /* WE-19 removed the pointer from struct iw_point */
4456                         char *dpos = (char *) &iwe_buf.u.data.length;
4457                         int dlen = dpos - (char *) &iwe_buf;
4458                         os_memcpy(dpos, pos + IW_EV_LCP_LEN,
4459                                   sizeof(struct iw_event) - dlen);
4460                 } else {
4461                         os_memcpy(&iwe_buf, pos, sizeof(struct iw_event));
4462                         custom += IW_EV_POINT_OFF;
4463                 }
4464
4465                 switch (iwe->cmd) {
4466                 case SIOCGIWAP:
4467                         if (!first)
4468                                 i802_add_neighbor(drv, bssid, freq, ie,
4469                                                   ie_len);
4470                         first = 0;
4471                         os_memcpy(bssid, iwe->u.ap_addr.sa_data, ETH_ALEN);
4472                         freq = 0;
4473                         ie = NULL;
4474                         ie_len = 0;
4475                         break;
4476                 case SIOCGIWFREQ:
4477                         i802_get_scan_freq(iwe, &freq);
4478                         break;
4479                 case IWEVGENIE:
4480                         if (custom + iwe->u.data.length > end) {
4481                                 wpa_printf(MSG_ERROR, "IWEVGENIE overflow");
4482                                 return -1;
4483                         }
4484                         ie = (u8 *) custom;
4485                         ie_len = iwe->u.data.length;
4486                         break;
4487                 }
4488
4489                 pos += iwe->len;
4490         }
4491
4492         if (!first)
4493                 i802_add_neighbor(drv, bssid, freq, ie, ie_len);
4494
4495         return 0;
4496 }
4497
4498
4499 static int i802_get_ht_scan_res(struct wpa_driver_nl80211_data *drv)
4500 {
4501         struct iwreq iwr;
4502         u8 *res_buf;
4503         size_t res_buf_len;
4504         int res;
4505
4506         res_buf_len = IW_SCAN_MAX_DATA;
4507         for (;;) {
4508                 res_buf = os_malloc(res_buf_len);
4509                 if (res_buf == NULL)
4510                         return -1;
4511                 os_memset(&iwr, 0, sizeof(iwr));
4512                 os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
4513                 iwr.u.data.pointer = res_buf;
4514                 iwr.u.data.length = res_buf_len;
4515
4516                 if (ioctl(drv->ioctl_sock, SIOCGIWSCAN, &iwr) == 0)
4517                         break;
4518
4519                 if (errno == E2BIG && res_buf_len < 65535) {
4520                         os_free(res_buf);
4521                         res_buf = NULL;
4522                         res_buf_len *= 2;
4523                         if (res_buf_len > 65535)
4524                                 res_buf_len = 65535; /* 16-bit length field */
4525                         wpa_printf(MSG_DEBUG, "Scan results did not fit - "
4526                                    "trying larger buffer (%lu bytes)",
4527                                    (unsigned long) res_buf_len);
4528                 } else {
4529                         perror("ioctl[SIOCGIWSCAN]");
4530                         os_free(res_buf);
4531                         return -1;
4532                 }
4533         }
4534
4535         if (iwr.u.data.length > res_buf_len) {
4536                 os_free(res_buf);
4537                 return -1;
4538         }
4539
4540         res = i802_parse_scan(drv, res_buf, iwr.u.data.length);
4541         os_free(res_buf);
4542
4543         return res;
4544 }
4545
4546
4547 static int i802_is_event_wireless_scan_complete(char *data, int len)
4548 {
4549         struct iw_event iwe_buf, *iwe = &iwe_buf;
4550         char *pos, *end;
4551
4552         pos = data;
4553         end = data + len;
4554
4555         while (pos + IW_EV_LCP_LEN <= end) {
4556                 /* Event data may be unaligned, so make a local, aligned copy
4557                  * before processing. */
4558                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
4559                 if (iwe->cmd == SIOCGIWSCAN)
4560                         return 1;
4561
4562                 pos += iwe->len;
4563         }
4564
4565         return 0;
4566 }
4567
4568
4569 static int i802_is_rtm_scan_complete(int ifindex, struct nlmsghdr *h, int len)
4570 {
4571         struct ifinfomsg *ifi;
4572         int attrlen, _nlmsg_len, rta_len;
4573         struct rtattr *attr;
4574
4575         if (len < (int) sizeof(*ifi))
4576                 return 0;
4577
4578         ifi = NLMSG_DATA(h);
4579
4580         if (ifindex != ifi->ifi_index)
4581                 return 0; /* event for foreign ifindex */
4582
4583         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
4584
4585         attrlen = h->nlmsg_len - _nlmsg_len;
4586         if (attrlen < 0)
4587                 return 0;
4588
4589         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
4590
4591         rta_len = RTA_ALIGN(sizeof(struct rtattr));
4592         while (RTA_OK(attr, attrlen)) {
4593                 if (attr->rta_type == IFLA_WIRELESS &&
4594                     i802_is_event_wireless_scan_complete(
4595                             ((char *) attr) + rta_len,
4596                             attr->rta_len - rta_len))
4597                         return 1;
4598                 attr = RTA_NEXT(attr, attrlen);
4599         }
4600
4601         return 0;
4602 }
4603
4604
4605 static int i802_is_scan_complete(int s, int ifindex)
4606 {
4607         char buf[1024];
4608         int left;
4609         struct nlmsghdr *h;
4610
4611         left = recv(s, buf, sizeof(buf), MSG_DONTWAIT);
4612         if (left < 0) {
4613                 perror("recv(netlink)");
4614                 return 0;
4615         }
4616
4617         h = (struct nlmsghdr *) buf;
4618         while (left >= (int) sizeof(*h)) {
4619                 int len, plen;
4620
4621                 len = h->nlmsg_len;
4622                 plen = len - sizeof(*h);
4623                 if (len > left || plen < 0) {
4624                         wpa_printf(MSG_DEBUG, "Malformed netlink message: "
4625                                    "len=%d left=%d plen=%d",
4626                                    len, left, plen);
4627                         break;
4628                 }
4629
4630                 switch (h->nlmsg_type) {
4631                 case RTM_NEWLINK:
4632                         if (i802_is_rtm_scan_complete(ifindex, h, plen))
4633                                 return 1;
4634                         break;
4635                 }
4636
4637                 len = NLMSG_ALIGN(len);
4638                 left -= len;
4639                 h = (struct nlmsghdr *) ((char *) h + len);
4640         }
4641
4642         return 0;
4643 }
4644
4645
4646 static int i802_ht_scan(struct wpa_driver_nl80211_data *drv)
4647 {
4648         struct iwreq iwr;
4649         int s, res, ifindex;
4650         struct sockaddr_nl local;
4651         time_t now, end;
4652         fd_set rfds;
4653         struct timeval tv;
4654
4655         wpa_printf(MSG_DEBUG, "nl80211: Scanning overlapping BSSes before "
4656                    "starting HT 20/40 MHz BSS");
4657
4658         /* Request a new scan */
4659         /* TODO: would be enough to scan the selected band */
4660         os_memset(&iwr, 0, sizeof(iwr));
4661         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
4662         if (ioctl(drv->ioctl_sock, SIOCSIWSCAN, &iwr) < 0) {
4663                 perror("ioctl[SIOCSIWSCAN]");
4664                 return -1;
4665         }
4666
4667         ifindex = if_nametoindex(drv->ifname);
4668
4669         /* Wait for scan completion event or timeout */
4670         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
4671         if (s < 0) {
4672                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
4673                 return -1;
4674         }
4675
4676         os_memset(&local, 0, sizeof(local));
4677         local.nl_family = AF_NETLINK;
4678         local.nl_groups = RTMGRP_LINK;
4679         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
4680                 perror("bind(netlink)");
4681                 close(s);
4682                 return -1;
4683         }
4684
4685         time(&end);
4686         end += 30; /* Wait at most 30 seconds for scan results */
4687         for (;;) {
4688                 time(&now);
4689                 tv.tv_sec = end > now ? end - now : 0;
4690                 tv.tv_usec = 0;
4691                 FD_ZERO(&rfds);
4692                 FD_SET(s, &rfds);
4693                 res = select(s + 1, &rfds, NULL, NULL, &tv);
4694                 if (res < 0) {
4695                         perror("select");
4696                         /* Assume results are ready after 10 seconds wait */
4697                         os_sleep(10, 0);
4698                         break;
4699                 } else if (res) {
4700                         if (i802_is_scan_complete(s, ifindex)) {
4701                                 wpa_printf(MSG_DEBUG, "nl80211: Scan "
4702                                            "completed");
4703                                 break;
4704                         }
4705                 } else {
4706                         wpa_printf(MSG_DEBUG, "nl80211: Scan timeout");
4707                         /* Assume results are ready to be read now */
4708                         break;
4709                 }
4710         }
4711
4712         close(s);
4713
4714         return i802_get_ht_scan_res(drv);
4715 }
4716 #endif /* CONFIG_IEEE80211N */
4717
4718
4719 static int i802_init_sockets(struct wpa_driver_nl80211_data *drv, const u8 *bssid)
4720 {
4721         struct ifreq ifr;
4722
4723         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
4724         if (drv->ioctl_sock < 0) {
4725                 perror("socket[PF_INET,SOCK_DGRAM]");
4726                 return -1;
4727         }
4728
4729         /* start listening for EAPOL on the default AP interface */
4730         add_ifidx(drv, if_nametoindex(drv->ifname));
4731
4732         if (hostapd_set_iface_flags(drv, drv->ifname, 0))
4733                 return -1;
4734
4735         if (bssid) {
4736                 os_strlcpy(ifr.ifr_name, drv->ifname, IFNAMSIZ);
4737                 memcpy(ifr.ifr_hwaddr.sa_data, bssid, ETH_ALEN);
4738                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
4739
4740                 if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifr)) {
4741                         perror("ioctl(SIOCSIFHWADDR)");
4742                         return -1;
4743                 }
4744         }
4745
4746         /*
4747          * initialise generic netlink and nl80211
4748          */
4749         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
4750         if (!drv->nl_cb) {
4751                 printf("Failed to allocate netlink callbacks.\n");
4752                 return -1;
4753         }
4754
4755         drv->nl_handle = nl_handle_alloc_cb(drv->nl_cb);
4756         if (!drv->nl_handle) {
4757                 printf("Failed to allocate netlink handle.\n");
4758                 return -1;
4759         }
4760
4761         if (genl_connect(drv->nl_handle)) {
4762                 printf("Failed to connect to generic netlink.\n");
4763                 return -1;
4764         }
4765
4766 #ifdef CONFIG_LIBNL20
4767         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
4768                 printf("Failed to allocate generic netlink cache.\n");
4769                 return -1;
4770         }
4771 #else /* CONFIG_LIBNL20 */
4772         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
4773         if (!drv->nl_cache) {
4774                 printf("Failed to allocate generic netlink cache.\n");
4775                 return -1;
4776         }
4777 #endif /* CONFIG_LIBNL20 */
4778
4779         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
4780         if (!drv->nl80211) {
4781                 printf("nl80211 not found.\n");
4782                 return -1;
4783         }
4784
4785 #ifdef CONFIG_IEEE80211N
4786         if (drv->ht_40mhz_scan) {
4787                 if (nl80211_set_mode(drv, drv->ifname, NL80211_IFTYPE_STATION)
4788                     || hostapd_set_iface_flags(drv, drv->ifname, 1) ||
4789                     i802_ht_scan(drv) ||
4790                     hostapd_set_iface_flags(drv, drv->ifname, 0)) {
4791                         wpa_printf(MSG_ERROR, "Failed to scan channels for "
4792                                    "HT 40 MHz operations");
4793                         return -1;
4794                 }
4795         }
4796 #endif /* CONFIG_IEEE80211N */
4797
4798         /* Initialise a monitor interface */
4799         if (nl80211_create_monitor_interface(drv))
4800                 return -1;
4801
4802         if (nl80211_set_mode(drv, drv->ifname, NL80211_IFTYPE_AP))
4803                 goto fail1;
4804
4805         if (hostapd_set_iface_flags(drv, drv->ifname, 1))
4806                 goto fail1;
4807
4808         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
4809         if (drv->eapol_sock < 0) {
4810                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
4811                 goto fail1;
4812         }
4813
4814         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
4815         {
4816                 printf("Could not register read socket for eapol\n");
4817                 return -1;
4818         }
4819
4820         memset(&ifr, 0, sizeof(ifr));
4821         os_strlcpy(ifr.ifr_name, drv->ifname, sizeof(ifr.ifr_name));
4822         if (ioctl(drv->ioctl_sock, SIOCGIFHWADDR, &ifr) != 0) {
4823                 perror("ioctl(SIOCGIFHWADDR)");
4824                 goto fail1;
4825         }
4826
4827         if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
4828                 printf("Invalid HW-addr family 0x%04x\n",
4829                        ifr.ifr_hwaddr.sa_family);
4830                 goto fail1;
4831         }
4832         memcpy(drv->hapd->own_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
4833
4834         return 0;
4835
4836 fail1:
4837         nl80211_remove_iface(drv, drv->monitor_ifidx);
4838         return -1;
4839 }
4840
4841
4842 static int i802_get_inact_sec(void *priv, const u8 *addr)
4843 {
4844         struct hostap_sta_driver_data data;
4845         int ret;
4846
4847         data.inactive_msec = (unsigned long) -1;
4848         ret = i802_read_sta_data(priv, &data, addr);
4849         if (ret || data.inactive_msec == (unsigned long) -1)
4850                 return -1;
4851         return data.inactive_msec / 1000;
4852 }
4853
4854
4855 static int i802_sta_clear_stats(void *priv, const u8 *addr)
4856 {
4857 #if 0
4858         /* TODO */
4859 #endif
4860         return 0;
4861 }
4862
4863
4864 static void
4865 hostapd_wireless_event_wireless_custom(struct wpa_driver_nl80211_data *drv,
4866                                        char *custom)
4867 {
4868         wpa_printf(MSG_DEBUG, "Custom wireless event: '%s'", custom);
4869
4870         if (strncmp(custom, "MLME-MICHAELMICFAILURE.indication", 33) == 0) {
4871                 char *pos;
4872                 u8 addr[ETH_ALEN];
4873                 pos = strstr(custom, "addr=");
4874                 if (pos == NULL) {
4875                         wpa_printf(MSG_DEBUG,
4876                                    "MLME-MICHAELMICFAILURE.indication "
4877                                    "without sender address ignored");
4878                         return;
4879                 }
4880                 pos += 5;
4881                 if (hwaddr_aton(pos, addr) == 0) {
4882                         hostapd_michael_mic_failure(drv->hapd, addr);
4883                 } else {
4884                         wpa_printf(MSG_DEBUG,
4885                                    "MLME-MICHAELMICFAILURE.indication "
4886                                    "with invalid MAC address");
4887                 }
4888         }
4889 }
4890
4891
4892 static void hostapd_wireless_event_wireless(struct wpa_driver_nl80211_data *drv,
4893                                             char *data, int len)
4894 {
4895         struct iw_event iwe_buf, *iwe = &iwe_buf;
4896         char *pos, *end, *custom, *buf;
4897
4898         pos = data;
4899         end = data + len;
4900
4901         while (pos + IW_EV_LCP_LEN <= end) {
4902                 /* Event data may be unaligned, so make a local, aligned copy
4903                  * before processing. */
4904                 memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
4905                 wpa_printf(MSG_DEBUG, "Wireless event: cmd=0x%x len=%d",
4906                            iwe->cmd, iwe->len);
4907                 if (iwe->len <= IW_EV_LCP_LEN)
4908                         return;
4909
4910                 custom = pos + IW_EV_POINT_LEN;
4911                 if (drv->we_version > 18 &&
4912                     (iwe->cmd == IWEVMICHAELMICFAILURE ||
4913                      iwe->cmd == IWEVCUSTOM)) {
4914                         /* WE-19 removed the pointer from struct iw_point */
4915                         char *dpos = (char *) &iwe_buf.u.data.length;
4916                         int dlen = dpos - (char *) &iwe_buf;
4917                         memcpy(dpos, pos + IW_EV_LCP_LEN,
4918                                sizeof(struct iw_event) - dlen);
4919                 } else {
4920                         memcpy(&iwe_buf, pos, sizeof(struct iw_event));
4921                         custom += IW_EV_POINT_OFF;
4922                 }
4923
4924                 switch (iwe->cmd) {
4925                 case IWEVCUSTOM:
4926                         if (custom + iwe->u.data.length > end)
4927                                 return;
4928                         buf = malloc(iwe->u.data.length + 1);
4929                         if (buf == NULL)
4930                                 return;
4931                         memcpy(buf, custom, iwe->u.data.length);
4932                         buf[iwe->u.data.length] = '\0';
4933                         hostapd_wireless_event_wireless_custom(drv, buf);
4934                         free(buf);
4935                         break;
4936                 }
4937
4938                 pos += iwe->len;
4939         }
4940 }
4941
4942
4943 static void hostapd_wireless_event_rtm_newlink(struct wpa_driver_nl80211_data *drv,
4944                                                struct nlmsghdr *h, int len)
4945 {
4946         struct ifinfomsg *ifi;
4947         int attrlen, _nlmsg_len, rta_len;
4948         struct rtattr *attr;
4949
4950         if (len < (int) sizeof(*ifi))
4951                 return;
4952
4953         ifi = NLMSG_DATA(h);
4954
4955         /* TODO: use ifi->ifi_index to filter out wireless events from other
4956          * interfaces */
4957
4958         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
4959
4960         attrlen = h->nlmsg_len - _nlmsg_len;
4961         if (attrlen < 0)
4962                 return;
4963
4964         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
4965
4966         rta_len = RTA_ALIGN(sizeof(struct rtattr));
4967         while (RTA_OK(attr, attrlen)) {
4968                 if (attr->rta_type == IFLA_WIRELESS) {
4969                         hostapd_wireless_event_wireless(
4970                                 drv, ((char *) attr) + rta_len,
4971                                 attr->rta_len - rta_len);
4972                 }
4973                 attr = RTA_NEXT(attr, attrlen);
4974         }
4975 }
4976
4977
4978 static void hostapd_wireless_event_receive(int sock, void *eloop_ctx,
4979                                            void *sock_ctx)
4980 {
4981         char buf[256];
4982         int left;
4983         struct sockaddr_nl from;
4984         socklen_t fromlen;
4985         struct nlmsghdr *h;
4986         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4987
4988         fromlen = sizeof(from);
4989         left = recvfrom(sock, buf, sizeof(buf), MSG_DONTWAIT,
4990                         (struct sockaddr *) &from, &fromlen);
4991         if (left < 0) {
4992                 if (errno != EINTR && errno != EAGAIN)
4993                         perror("recvfrom(netlink)");
4994                 return;
4995         }
4996
4997         h = (struct nlmsghdr *) buf;
4998         while (left >= (int) sizeof(*h)) {
4999                 int len, plen;
5000
5001                 len = h->nlmsg_len;
5002                 plen = len - sizeof(*h);
5003                 if (len > left || plen < 0) {
5004                         printf("Malformed netlink message: "
5005                                "len=%d left=%d plen=%d\n",
5006                                len, left, plen);
5007                         break;
5008                 }
5009
5010                 switch (h->nlmsg_type) {
5011                 case RTM_NEWLINK:
5012                         hostapd_wireless_event_rtm_newlink(drv, h, plen);
5013                         break;
5014                 }
5015
5016                 len = NLMSG_ALIGN(len);
5017                 left -= len;
5018                 h = (struct nlmsghdr *) ((char *) h + len);
5019         }
5020
5021         if (left > 0) {
5022                 printf("%d extra bytes in the end of netlink message\n", left);
5023         }
5024 }
5025
5026
5027 static int hostap_get_we_version(struct wpa_driver_nl80211_data *drv)
5028 {
5029         struct iw_range *range;
5030         struct iwreq iwr;
5031         int minlen;
5032         size_t buflen;
5033
5034         drv->we_version = 0;
5035
5036         /*
5037          * Use larger buffer than struct iw_range in order to allow the
5038          * structure to grow in the future.
5039          */
5040         buflen = sizeof(struct iw_range) + 500;
5041         range = os_zalloc(buflen);
5042         if (range == NULL)
5043                 return -1;
5044
5045         memset(&iwr, 0, sizeof(iwr));
5046         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
5047         iwr.u.data.pointer = (caddr_t) range;
5048         iwr.u.data.length = buflen;
5049
5050         minlen = ((char *) &range->enc_capa) - (char *) range +
5051                 sizeof(range->enc_capa);
5052
5053         if (ioctl(drv->ioctl_sock, SIOCGIWRANGE, &iwr) < 0) {
5054                 perror("ioctl[SIOCGIWRANGE]");
5055                 free(range);
5056                 return -1;
5057         } else if (iwr.u.data.length >= minlen &&
5058                    range->we_version_compiled >= 18) {
5059                 wpa_printf(MSG_DEBUG, "SIOCGIWRANGE: WE(compiled)=%d "
5060                            "WE(source)=%d enc_capa=0x%x",
5061                            range->we_version_compiled,
5062                            range->we_version_source,
5063                            range->enc_capa);
5064                 drv->we_version = range->we_version_compiled;
5065         }
5066
5067         free(range);
5068         return 0;
5069 }
5070
5071
5072 static int i802_wireless_event_init(struct wpa_driver_nl80211_data *drv)
5073 {
5074         int s;
5075         struct sockaddr_nl local;
5076
5077         hostap_get_we_version(drv);
5078
5079         drv->wext_sock = -1;
5080
5081         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
5082         if (s < 0) {
5083                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
5084                 return -1;
5085         }
5086
5087         memset(&local, 0, sizeof(local));
5088         local.nl_family = AF_NETLINK;
5089         local.nl_groups = RTMGRP_LINK;
5090         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
5091                 perror("bind(netlink)");
5092                 close(s);
5093                 return -1;
5094         }
5095
5096         eloop_register_read_sock(s, hostapd_wireless_event_receive, drv,
5097                                  NULL);
5098         drv->wext_sock = s;
5099
5100         return 0;
5101 }
5102
5103
5104 static void i802_wireless_event_deinit(struct wpa_driver_nl80211_data *drv)
5105 {
5106         if (drv->wext_sock < 0)
5107                 return;
5108         eloop_unregister_read_sock(drv->wext_sock);
5109         close(drv->wext_sock);
5110 }
5111
5112
5113 static int i802_sta_deauth(void *priv, const u8 *addr, int reason)
5114 {
5115         struct wpa_driver_nl80211_data *drv = priv;
5116         struct ieee80211_mgmt mgmt;
5117
5118         memset(&mgmt, 0, sizeof(mgmt));
5119         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5120                                           WLAN_FC_STYPE_DEAUTH);
5121         memcpy(mgmt.da, addr, ETH_ALEN);
5122         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
5123         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
5124         mgmt.u.deauth.reason_code = host_to_le16(reason);
5125         return i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
5126                                       sizeof(mgmt.u.deauth), 0);
5127 }
5128
5129
5130 static int i802_sta_disassoc(void *priv, const u8 *addr, int reason)
5131 {
5132         struct wpa_driver_nl80211_data *drv = priv;
5133         struct ieee80211_mgmt mgmt;
5134
5135         memset(&mgmt, 0, sizeof(mgmt));
5136         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5137                                           WLAN_FC_STYPE_DISASSOC);
5138         memcpy(mgmt.da, addr, ETH_ALEN);
5139         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
5140         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
5141         mgmt.u.disassoc.reason_code = host_to_le16(reason);
5142         return  i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
5143                                        sizeof(mgmt.u.disassoc), 0);
5144 }
5145
5146
5147 static const struct hostapd_neighbor_bss *
5148 i802_get_neighbor_bss(void *priv, size_t *num)
5149 {
5150         struct wpa_driver_nl80211_data *drv = priv;
5151         *num = drv->num_neighbors;
5152         return drv->neighbors;
5153 }
5154
5155
5156 static void *i802_init_bssid(struct hostapd_data *hapd, const u8 *bssid)
5157 {
5158         struct wpa_driver_nl80211_data *drv;
5159         size_t i;
5160
5161         drv = os_zalloc(sizeof(struct wpa_driver_nl80211_data));
5162         if (drv == NULL) {
5163                 printf("Could not allocate memory for i802 driver data\n");
5164                 return NULL;
5165         }
5166
5167         drv->hapd = hapd;
5168         memcpy(drv->ifname, hapd->conf->iface, sizeof(drv->ifname));
5169         memcpy(drv->bss.ifname, hapd->conf->iface, sizeof(drv->bss.ifname));
5170         drv->ifindex = if_nametoindex(drv->ifname);
5171
5172         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
5173         drv->if_indices = drv->default_if_indices;
5174         for (i = 0; i < hapd->iface->num_bss; i++) {
5175                 struct hostapd_data *bss = hapd->iface->bss[i];
5176                 if (bss->conf->bridge)
5177                         add_ifidx(drv, if_nametoindex(bss->conf->bridge));
5178         }
5179         drv->ht_40mhz_scan = hapd->iconf->secondary_channel != 0;
5180
5181         if (i802_init_sockets(drv, bssid))
5182                 goto failed;
5183
5184         if (i802_wireless_event_init(drv))
5185                 goto failed;
5186
5187         return drv;
5188
5189 failed:
5190         free(drv);
5191         return NULL;
5192 }
5193
5194
5195 static void *i802_init(struct hostapd_data *hapd)
5196 {
5197         return i802_init_bssid(hapd, NULL);
5198 }
5199
5200
5201 static void i802_deinit(void *priv)
5202 {
5203         struct wpa_driver_nl80211_data *drv = priv;
5204         struct i802_bss *bss, *prev;
5205
5206         i802_wireless_event_deinit(drv);
5207
5208         if (drv->last_freq_ht) {
5209                 /* Clear HT flags from the driver */
5210                 struct hostapd_freq_params freq;
5211                 os_memset(&freq, 0, sizeof(freq));
5212                 freq.freq = drv->last_freq;
5213                 i802_set_freq(priv, &freq);
5214         }
5215
5216         i802_del_beacon(drv);
5217
5218         /* remove monitor interface */
5219         nl80211_remove_iface(drv, drv->monitor_ifidx);
5220
5221         (void) hostapd_set_iface_flags(drv, drv->ifname, 0);
5222
5223         if (drv->monitor_sock >= 0) {
5224                 eloop_unregister_read_sock(drv->monitor_sock);
5225                 close(drv->monitor_sock);
5226         }
5227         if (drv->ioctl_sock >= 0)
5228                 close(drv->ioctl_sock);
5229         if (drv->eapol_sock >= 0) {
5230                 eloop_unregister_read_sock(drv->eapol_sock);
5231                 close(drv->eapol_sock);
5232         }
5233
5234         genl_family_put(drv->nl80211);
5235         nl_cache_free(drv->nl_cache);
5236         nl_handle_destroy(drv->nl_handle);
5237         nl_cb_put(drv->nl_cb);
5238
5239         if (drv->if_indices != drv->default_if_indices)
5240                 free(drv->if_indices);
5241
5242         os_free(drv->neighbors);
5243
5244         bss = drv->bss.next;
5245         while (bss) {
5246                 prev = bss;
5247                 bss = bss->next;
5248                 os_free(bss);
5249         }
5250
5251         free(drv);
5252 }
5253
5254 #endif /* HOSTAPD */
5255
5256
5257 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
5258         .name = "nl80211",
5259         .desc = "Linux nl80211/cfg80211",
5260         .get_bssid = wpa_driver_nl80211_get_bssid,
5261         .get_ssid = wpa_driver_nl80211_get_ssid,
5262         .set_key = wpa_driver_nl80211_set_key,
5263         .scan2 = wpa_driver_nl80211_scan,
5264         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
5265         .deauthenticate = wpa_driver_nl80211_deauthenticate,
5266         .disassociate = wpa_driver_nl80211_disassociate,
5267         .authenticate = wpa_driver_nl80211_authenticate,
5268         .associate = wpa_driver_nl80211_associate,
5269         .init = wpa_driver_nl80211_init,
5270         .deinit = wpa_driver_nl80211_deinit,
5271         .get_capa = wpa_driver_nl80211_get_capa,
5272         .set_operstate = wpa_driver_nl80211_set_operstate,
5273         .set_country = wpa_driver_nl80211_set_country,
5274 #ifdef CONFIG_AP
5275         .set_beacon = wpa_driver_nl80211_set_beacon,
5276         .set_beacon_int = wpa_driver_nl80211_set_beacon_int,
5277         .send_mlme = wpa_driver_nl80211_send_mlme,
5278 #endif /* CONFIG_AP */
5279 #if defined(CONFIG_AP) || defined(HOSTAPD)
5280         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
5281 #endif /* CONFIG_AP || HOSTAPD */
5282 #ifdef HOSTAPD
5283         .hapd_init = i802_init,
5284         .init_bssid = i802_init_bssid,
5285         .hapd_deinit = i802_deinit,
5286         .hapd_set_key = i802_set_key,
5287         .get_seqnum = i802_get_seqnum,
5288         .flush = i802_flush,
5289         .read_sta_data = i802_read_sta_data,
5290         .hapd_send_eapol = i802_send_eapol,
5291         .sta_set_flags = i802_sta_set_flags,
5292         .sta_deauth = i802_sta_deauth,
5293         .sta_disassoc = i802_sta_disassoc,
5294         .sta_remove = i802_sta_remove,
5295         .send_mgmt_frame = i802_send_mgmt_frame,
5296         .sta_add = i802_sta_add,
5297         .get_inact_sec = i802_get_inact_sec,
5298         .sta_clear_stats = i802_sta_clear_stats,
5299         .set_freq = i802_set_freq,
5300         .set_rts = i802_set_rts,
5301         .set_frag = i802_set_frag,
5302         .set_retry = i802_set_retry,
5303         .set_rate_sets = i802_set_rate_sets,
5304         .hapd_set_beacon = i802_set_beacon,
5305         .hapd_set_beacon_int = i802_set_beacon_int,
5306         .set_cts_protect = i802_set_cts_protect,
5307         .set_preamble = i802_set_preamble,
5308         .set_short_slot_time = i802_set_short_slot_time,
5309         .set_tx_queue_params = i802_set_tx_queue_params,
5310         .bss_add = i802_bss_add,
5311         .bss_remove = i802_bss_remove,
5312         .if_add = i802_if_add,
5313         .if_update = i802_if_update,
5314         .if_remove = i802_if_remove,
5315         .set_sta_vlan = i802_set_sta_vlan,
5316         .hapd_set_country = i802_set_country,
5317         .get_neighbor_bss = i802_get_neighbor_bss,
5318 #endif /* HOSTAPD */
5319 };