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