Remove flags parameter from send_mgmt_frame() driver op
[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 #endif /* CONFIG_AP || HOSTAPD */
1964
1965
1966 #ifdef CONFIG_AP
1967
1968 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
1969                                          const void *data, size_t len,
1970                                          int encrypt)
1971 {
1972         __u8 rtap_hdr[] = {
1973                 0x00, 0x00, /* radiotap version */
1974                 0x0e, 0x00, /* radiotap length */
1975                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
1976                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
1977                 0x00,       /* padding */
1978                 0x00, 0x00, /* RX and TX flags to indicate that */
1979                 0x00, 0x00, /* this is the injected frame directly */
1980         };
1981         struct iovec iov[2] = {
1982                 {
1983                         .iov_base = &rtap_hdr,
1984                         .iov_len = sizeof(rtap_hdr),
1985                 },
1986                 {
1987                         .iov_base = (void *) data,
1988                         .iov_len = len,
1989                 }
1990         };
1991         struct msghdr msg = {
1992                 .msg_name = NULL,
1993                 .msg_namelen = 0,
1994                 .msg_iov = iov,
1995                 .msg_iovlen = 2,
1996                 .msg_control = NULL,
1997                 .msg_controllen = 0,
1998                 .msg_flags = 0,
1999         };
2000
2001         if (encrypt)
2002                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
2003
2004         return sendmsg(drv->monitor_sock, &msg, 0);
2005 }
2006
2007
2008 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
2009                                         size_t data_len)
2010 {
2011         struct wpa_driver_nl80211_data *drv = priv;
2012         struct ieee80211_mgmt *mgmt;
2013         int do_not_encrypt = 0;
2014         u16 fc;
2015
2016         mgmt = (struct ieee80211_mgmt *) data;
2017         fc = le_to_host16(mgmt->frame_control);
2018
2019         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
2020             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
2021                 /*
2022                  * Only one of the authentication frame types is encrypted.
2023                  * In order for static WEP encryption to work properly (i.e.,
2024                  * to not encrypt the frame), we need to tell mac80211 about
2025                  * the frames that must not be encrypted.
2026                  */
2027                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
2028                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
2029                 if (auth_alg == WLAN_AUTH_OPEN ||
2030                     (auth_alg == WLAN_AUTH_SHARED_KEY && auth_trans != 3))
2031                         do_not_encrypt = 1;
2032         }
2033
2034         return wpa_driver_nl80211_send_frame(drv, data, data_len,
2035                                              !do_not_encrypt);
2036 }
2037
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 static int i802_send_frame(void *priv, const void *data, size_t len,
3042                            int encrypt)
3043 {
3044         __u8 rtap_hdr[] = {
3045                 0x00, 0x00, /* radiotap version */
3046                 0x0e, 0x00, /* radiotap length */
3047                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
3048                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
3049                 0x00,       /* padding */
3050                 0x00, 0x00, /* RX and TX flags to indicate that */
3051                 0x00, 0x00, /* this is the injected frame directly */
3052         };
3053         struct wpa_driver_nl80211_data *drv = priv;
3054         struct iovec iov[2] = {
3055                 {
3056                         .iov_base = &rtap_hdr,
3057                         .iov_len = sizeof(rtap_hdr),
3058                 },
3059                 {
3060                         .iov_base = (void*)data,
3061                         .iov_len = len,
3062                 }
3063         };
3064         struct msghdr msg = {
3065                 .msg_name = NULL,
3066                 .msg_namelen = 0,
3067                 .msg_iov = iov,
3068                 .msg_iovlen = 2,
3069                 .msg_control = NULL,
3070                 .msg_controllen = 0,
3071                 .msg_flags = 0,
3072         };
3073
3074         if (encrypt)
3075                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
3076
3077         return sendmsg(drv->monitor_sock, &msg, 0);
3078 }
3079
3080 static int i802_send_mgmt_frame(void *priv, const void *data, size_t len)
3081 {
3082         struct ieee80211_mgmt *mgmt;
3083         int do_not_encrypt = 0;
3084         u16 fc;
3085
3086         mgmt = (struct ieee80211_mgmt *) data;
3087         fc = le_to_host16(mgmt->frame_control);
3088
3089         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3090             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
3091                 /*
3092                  * Only one of the authentication frame types is encrypted.
3093                  * In order for static WEP encryption to work properly (i.e.,
3094                  * to not encrypt the frame), we need to tell mac80211 about
3095                  * the frames that must not be encrypted.
3096                  */
3097                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
3098                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
3099                 if (auth_alg == WLAN_AUTH_OPEN ||
3100                     (auth_alg == WLAN_AUTH_SHARED_KEY && auth_trans != 3))
3101                         do_not_encrypt = 1;
3102         }
3103
3104         return i802_send_frame(priv, data, len, !do_not_encrypt);
3105 }
3106
3107 /* Set kernel driver on given frequency (MHz) */
3108 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
3109 {
3110         struct wpa_driver_nl80211_data *drv = priv;
3111         struct nl_msg *msg;
3112
3113         msg = nlmsg_alloc();
3114         if (!msg)
3115                 return -1;
3116
3117         drv->last_freq = freq->freq;
3118         drv->last_freq_ht = freq->ht_enabled;
3119
3120         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3121                     NL80211_CMD_SET_WIPHY, 0);
3122
3123         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3124         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq->freq);
3125         if (freq->ht_enabled) {
3126                 switch (freq->sec_channel_offset) {
3127                 case -1:
3128                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3129                                     NL80211_CHAN_HT40MINUS);
3130                         break;
3131                 case 1:
3132                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3133                                     NL80211_CHAN_HT40PLUS);
3134                         break;
3135                 default:
3136                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3137                                     NL80211_CHAN_HT20);
3138                         break;
3139                 }
3140         }
3141
3142         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3143                 return 0;
3144  nla_put_failure:
3145         return -1;
3146 }
3147
3148
3149 static int i802_set_rts(void *priv, int rts)
3150 {
3151         struct wpa_driver_nl80211_data *drv = priv;
3152         struct iwreq iwr;
3153
3154         memset(&iwr, 0, sizeof(iwr));
3155         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
3156         iwr.u.rts.value = rts;
3157         iwr.u.rts.fixed = 1;
3158
3159         if (ioctl(drv->ioctl_sock, SIOCSIWRTS, &iwr) < 0) {
3160                 perror("ioctl[SIOCSIWRTS]");
3161                 return -1;
3162         }
3163
3164         return 0;
3165 }
3166
3167
3168 static int i802_set_frag(void *priv, int frag)
3169 {
3170         struct wpa_driver_nl80211_data *drv = priv;
3171         struct iwreq iwr;
3172
3173         memset(&iwr, 0, sizeof(iwr));
3174         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
3175         iwr.u.frag.value = frag;
3176         iwr.u.frag.fixed = 1;
3177
3178         if (ioctl(drv->ioctl_sock, SIOCSIWFRAG, &iwr) < 0) {
3179                 perror("ioctl[SIOCSIWFRAG]");
3180                 return -1;
3181         }
3182
3183         return 0;
3184 }
3185
3186
3187 static int i802_set_retry(void *priv, int short_retry, int long_retry)
3188 {
3189         struct wpa_driver_nl80211_data *drv = priv;
3190         struct iwreq iwr;
3191
3192         memset(&iwr, 0, sizeof(iwr));
3193         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
3194
3195         iwr.u.retry.value = short_retry;
3196         iwr.u.retry.flags = IW_RETRY_LIMIT | IW_RETRY_MIN;
3197         if (ioctl(drv->ioctl_sock, SIOCSIWRETRY, &iwr) < 0) {
3198                 perror("ioctl[SIOCSIWRETRY(short)]");
3199                 return -1;
3200         }
3201
3202         iwr.u.retry.value = long_retry;
3203         iwr.u.retry.flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
3204         if (ioctl(drv->ioctl_sock, SIOCSIWRETRY, &iwr) < 0) {
3205                 perror("ioctl[SIOCSIWRETRY(long)]");
3206                 return -1;
3207         }
3208
3209         return 0;
3210 }
3211
3212
3213 static int i802_flush(void *priv)
3214 {
3215         struct wpa_driver_nl80211_data *drv = priv;
3216         struct nl_msg *msg;
3217
3218         msg = nlmsg_alloc();
3219         if (!msg)
3220                 return -1;
3221
3222         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3223                     0, NL80211_CMD_DEL_STATION, 0);
3224
3225         /*
3226          * XXX: FIX! this needs to flush all VLANs too
3227          */
3228         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3229                     if_nametoindex(drv->ifname));
3230
3231         return send_and_recv_msgs(drv, msg, NULL, NULL);
3232  nla_put_failure:
3233         return -ENOBUFS;
3234 }
3235
3236
3237 static int get_sta_handler(struct nl_msg *msg, void *arg)
3238 {
3239         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3240         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3241         struct hostap_sta_driver_data *data = arg;
3242         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
3243         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
3244                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
3245                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
3246                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
3247                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
3248                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
3249         };
3250
3251         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3252                   genlmsg_attrlen(gnlh, 0), NULL);
3253
3254         /*
3255          * TODO: validate the interface and mac address!
3256          * Otherwise, there's a race condition as soon as
3257          * the kernel starts sending station notifications.
3258          */
3259
3260         if (!tb[NL80211_ATTR_STA_INFO]) {
3261                 wpa_printf(MSG_DEBUG, "sta stats missing!");
3262                 return NL_SKIP;
3263         }
3264         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
3265                              tb[NL80211_ATTR_STA_INFO],
3266                              stats_policy)) {
3267                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
3268                 return NL_SKIP;
3269         }
3270
3271         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
3272                 data->inactive_msec =
3273                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
3274         if (stats[NL80211_STA_INFO_RX_BYTES])
3275                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
3276         if (stats[NL80211_STA_INFO_TX_BYTES])
3277                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
3278         if (stats[NL80211_STA_INFO_RX_PACKETS])
3279                 data->rx_packets =
3280                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
3281         if (stats[NL80211_STA_INFO_TX_PACKETS])
3282                 data->tx_packets =
3283                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
3284
3285         return NL_SKIP;
3286 }
3287
3288 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
3289                               const u8 *addr)
3290 {
3291         struct wpa_driver_nl80211_data *drv = priv;
3292         struct nl_msg *msg;
3293
3294         os_memset(data, 0, sizeof(*data));
3295         msg = nlmsg_alloc();
3296         if (!msg)
3297                 return -ENOMEM;
3298
3299         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3300                     0, NL80211_CMD_GET_STATION, 0);
3301
3302         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3303         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3304
3305         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
3306  nla_put_failure:
3307         return -ENOBUFS;
3308 }
3309
3310
3311 static int i802_send_eapol(void *priv, const u8 *addr, const u8 *data,
3312                            size_t data_len, int encrypt, const u8 *own_addr)
3313 {
3314         struct wpa_driver_nl80211_data *drv = priv;
3315         struct ieee80211_hdr *hdr;
3316         size_t len;
3317         u8 *pos;
3318         int res;
3319 #if 0 /* FIX */
3320         int qos = sta->flags & WLAN_STA_WME;
3321 #else
3322         int qos = 0;
3323 #endif
3324
3325         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
3326                 data_len;
3327         hdr = os_zalloc(len);
3328         if (hdr == NULL) {
3329                 printf("malloc() failed for i802_send_data(len=%lu)\n",
3330                        (unsigned long) len);
3331                 return -1;
3332         }
3333
3334         hdr->frame_control =
3335                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
3336         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
3337         if (encrypt)
3338                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
3339 #if 0 /* To be enabled if qos determination is added above */
3340         if (qos) {
3341                 hdr->frame_control |=
3342                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
3343         }
3344 #endif
3345
3346         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
3347         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
3348         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
3349         pos = (u8 *) (hdr + 1);
3350
3351 #if 0 /* To be enabled if qos determination is added above */
3352         if (qos) {
3353                 /* add an empty QoS header if needed */
3354                 pos[0] = 0;
3355                 pos[1] = 0;
3356                 pos += 2;
3357         }
3358 #endif
3359
3360         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
3361         pos += sizeof(rfc1042_header);
3362         WPA_PUT_BE16(pos, ETH_P_PAE);
3363         pos += 2;
3364         memcpy(pos, data, data_len);
3365
3366         res = i802_send_frame(drv, (u8 *) hdr, len, encrypt);
3367         free(hdr);
3368
3369         if (res < 0) {
3370                 perror("i802_send_eapol: send");
3371                 printf("i802_send_eapol - packet len: %lu - failed\n",
3372                        (unsigned long) len);
3373         }
3374
3375         return res;
3376 }
3377
3378
3379 static int i802_sta_add(const char *ifname, void *priv,
3380                         struct hostapd_sta_add_params *params)
3381 {
3382         struct wpa_driver_nl80211_data *drv = priv;
3383         struct nl_msg *msg;
3384         int ret = -ENOBUFS;
3385
3386         msg = nlmsg_alloc();
3387         if (!msg)
3388                 return -ENOMEM;
3389
3390         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3391                     0, NL80211_CMD_NEW_STATION, 0);
3392
3393         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3394                     if_nametoindex(drv->ifname));
3395         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
3396         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
3397         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
3398                 params->supp_rates);
3399         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
3400                     params->listen_interval);
3401
3402 #ifdef CONFIG_IEEE80211N
3403         if (params->ht_capabilities) {
3404                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
3405                         params->ht_capabilities->length,
3406                         &params->ht_capabilities->data);
3407         }
3408 #endif /* CONFIG_IEEE80211N */
3409
3410         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3411         if (ret)
3412                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
3413                            "result: %d (%s)", ret, strerror(-ret));
3414         if (ret == -EEXIST)
3415                 ret = 0;
3416  nla_put_failure:
3417         return ret;
3418 }
3419
3420
3421 static int i802_sta_remove(void *priv, const u8 *addr)
3422 {
3423         struct wpa_driver_nl80211_data *drv = priv;
3424         struct nl_msg *msg;
3425         int ret;
3426
3427         msg = nlmsg_alloc();
3428         if (!msg)
3429                 return -ENOMEM;
3430
3431         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3432                     0, NL80211_CMD_DEL_STATION, 0);
3433
3434         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3435                     if_nametoindex(drv->ifname));
3436         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3437
3438         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3439         if (ret == -ENOENT)
3440                 return 0;
3441         return ret;
3442  nla_put_failure:
3443         return -ENOBUFS;
3444 }
3445
3446
3447 static int i802_sta_set_flags(void *priv, const u8 *addr,
3448                               int total_flags, int flags_or, int flags_and)
3449 {
3450         struct wpa_driver_nl80211_data *drv = priv;
3451         struct nl_msg *msg, *flags = NULL;
3452
3453         msg = nlmsg_alloc();
3454         if (!msg)
3455                 return -ENOMEM;
3456
3457         flags = nlmsg_alloc();
3458         if (!flags) {
3459                 nlmsg_free(msg);
3460                 return -ENOMEM;
3461         }
3462
3463         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3464                     0, NL80211_CMD_SET_STATION, 0);
3465
3466         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3467                     if_nametoindex(drv->ifname));
3468         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3469
3470         if (total_flags & WLAN_STA_AUTHORIZED)
3471                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
3472
3473         if (total_flags & WLAN_STA_WMM)
3474                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
3475
3476         if (total_flags & WLAN_STA_SHORT_PREAMBLE)
3477                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
3478
3479         if (total_flags & WLAN_STA_MFP)
3480                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
3481
3482         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
3483                 goto nla_put_failure;
3484
3485         nlmsg_free(flags);
3486
3487         return send_and_recv_msgs(drv, msg, NULL, NULL);
3488  nla_put_failure:
3489         nlmsg_free(flags);
3490         return -ENOBUFS;
3491 }
3492
3493
3494 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
3495                                     int cw_min, int cw_max, int burst_time)
3496 {
3497         struct wpa_driver_nl80211_data *drv = priv;
3498         struct nl_msg *msg;
3499         struct nlattr *txq, *params;
3500
3501         msg = nlmsg_alloc();
3502         if (!msg)
3503                 return -1;
3504
3505         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3506                     0, NL80211_CMD_SET_WIPHY, 0);
3507
3508         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3509
3510         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
3511         if (!txq)
3512                 goto nla_put_failure;
3513
3514         /* We are only sending parameters for a single TXQ at a time */
3515         params = nla_nest_start(msg, 1);
3516         if (!params)
3517                 goto nla_put_failure;
3518
3519         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, queue);
3520         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
3521          * 32 usec, so need to convert the value here. */
3522         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
3523         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
3524         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
3525         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
3526
3527         nla_nest_end(msg, params);
3528
3529         nla_nest_end(msg, txq);
3530
3531         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3532                 return 0;
3533  nla_put_failure:
3534         return -1;
3535 }
3536
3537
3538 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv, int ifidx)
3539 {
3540         struct nl_msg *msg;
3541
3542         /* stop listening for EAPOL on this interface */
3543         del_ifidx(drv, ifidx);
3544
3545         msg = nlmsg_alloc();
3546         if (!msg)
3547                 goto nla_put_failure;
3548
3549         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3550                     0, NL80211_CMD_DEL_INTERFACE, 0);
3551         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
3552
3553         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3554                 return;
3555  nla_put_failure:
3556         printf("Failed to remove interface.\n");
3557 }
3558
3559
3560 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
3561                                 const char *ifname,
3562                                 enum nl80211_iftype iftype,
3563                                 const u8 *addr)
3564 {
3565         struct nl_msg *msg, *flags = NULL;
3566         int ifidx;
3567         struct ifreq ifreq;
3568         struct iwreq iwr;
3569         int ret = -ENOBUFS;
3570
3571         msg = nlmsg_alloc();
3572         if (!msg)
3573                 return -1;
3574
3575         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3576                     0, NL80211_CMD_NEW_INTERFACE, 0);
3577         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3578         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
3579         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
3580
3581         if (iftype == NL80211_IFTYPE_MONITOR) {
3582                 int err;
3583
3584                 flags = nlmsg_alloc();
3585                 if (!flags)
3586                         goto nla_put_failure;
3587
3588                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
3589
3590                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
3591
3592                 nlmsg_free(flags);
3593
3594                 if (err)
3595                         goto nla_put_failure;
3596         }
3597
3598         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3599         if (ret) {
3600  nla_put_failure:
3601                 printf("Failed to create interface %s.\n", ifname);
3602                 return ret;
3603         }
3604
3605         ifidx = if_nametoindex(ifname);
3606
3607         if (ifidx <= 0)
3608                 return -1;
3609
3610         /* start listening for EAPOL on this interface */
3611         add_ifidx(drv, ifidx);
3612
3613         if (addr) {
3614                 switch (iftype) {
3615                 case NL80211_IFTYPE_AP:
3616                         os_strlcpy(ifreq.ifr_name, ifname, IFNAMSIZ);
3617                         memcpy(ifreq.ifr_hwaddr.sa_data, addr, ETH_ALEN);
3618                         ifreq.ifr_hwaddr.sa_family = ARPHRD_ETHER;
3619
3620                         if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifreq)) {
3621                                 nl80211_remove_iface(drv, ifidx);
3622                                 return -1;
3623                         }
3624                         break;
3625                 case NL80211_IFTYPE_WDS:
3626                         memset(&iwr, 0, sizeof(iwr));
3627                         os_strlcpy(iwr.ifr_name, ifname, IFNAMSIZ);
3628                         iwr.u.addr.sa_family = ARPHRD_ETHER;
3629                         memcpy(iwr.u.addr.sa_data, addr, ETH_ALEN);
3630                         if (ioctl(drv->ioctl_sock, SIOCSIWAP, &iwr))
3631                                 return -1;
3632                         break;
3633                 default:
3634                         /* nothing */
3635                         break;
3636                 }
3637         }
3638
3639         return ifidx;
3640 }
3641
3642
3643 static int i802_bss_add(void *priv, const char *ifname, const u8 *bssid)
3644 {
3645         struct wpa_driver_nl80211_data *drv = priv;
3646         int ifidx;
3647         struct i802_bss *bss;
3648
3649         bss = os_zalloc(sizeof(*bss));
3650         if (bss == NULL)
3651                 return -1;
3652         os_strlcpy(bss->ifname, ifname, IFNAMSIZ);
3653
3654         ifidx = nl80211_create_iface(priv, ifname, NL80211_IFTYPE_AP, bssid);
3655         if (ifidx < 0) {
3656                 os_free(bss);
3657                 return -1;
3658         }
3659         if (hostapd_set_iface_flags(priv, ifname, 1)) {
3660                 nl80211_remove_iface(priv, ifidx);
3661                 os_free(bss);
3662                 return -1;
3663         }
3664         bss->next = drv->bss.next;
3665         drv->bss.next = bss;
3666         return 0;
3667 }
3668
3669
3670 static int i802_bss_remove(void *priv, const char *ifname)
3671 {
3672         struct wpa_driver_nl80211_data *drv = priv;
3673         struct i802_bss *bss, *prev;
3674         nl80211_remove_iface(priv, if_nametoindex(ifname));
3675         prev = &drv->bss;
3676         bss = drv->bss.next;
3677         while (bss) {
3678                 if (os_strncmp(ifname, bss->ifname, IFNAMSIZ) == 0) {
3679                         prev->next = bss->next;
3680                         os_free(bss);
3681                         break;
3682                 }
3683                 prev = bss;
3684                 bss = bss->next;
3685         }
3686         return 0;
3687 }
3688
3689
3690 static int i802_set_beacon(const char *iface, void *priv,
3691                            const u8 *head, size_t head_len,
3692                            const u8 *tail, size_t tail_len, int dtim_period)
3693 {
3694         struct wpa_driver_nl80211_data *drv = priv;
3695         struct nl_msg *msg;
3696         u8 cmd = NL80211_CMD_NEW_BEACON;
3697         int ret;
3698         struct i802_bss *bss;
3699
3700         bss = get_bss(drv, iface);
3701         if (bss == NULL)
3702                 return -ENOENT;
3703
3704         msg = nlmsg_alloc();
3705         if (!msg)
3706                 return -ENOMEM;
3707
3708         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (iface=%s beacon_set=%d)",
3709                    iface, bss->beacon_set);
3710         if (bss->beacon_set)
3711                 cmd = NL80211_CMD_SET_BEACON;
3712
3713         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3714                     0, cmd, 0);
3715         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
3716         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
3717         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
3718         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, drv->beacon_int);
3719         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
3720
3721         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3722         if (!ret)
3723                 bss->beacon_set = 1;
3724         return ret;
3725  nla_put_failure:
3726         return -ENOBUFS;
3727 }
3728
3729
3730 static int i802_del_beacon(struct wpa_driver_nl80211_data *drv)
3731 {
3732         struct nl_msg *msg;
3733
3734         msg = nlmsg_alloc();
3735         if (!msg)
3736                 return -ENOMEM;
3737
3738         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3739                     0, NL80211_CMD_DEL_BEACON, 0);
3740         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3741
3742         return send_and_recv_msgs(drv, msg, NULL, NULL);
3743  nla_put_failure:
3744         return -ENOBUFS;
3745 }
3746
3747
3748 static int i802_set_beacon_int(void *priv, int value)
3749 {
3750         struct wpa_driver_nl80211_data *drv = priv;
3751         struct nl_msg *msg;
3752
3753         drv->beacon_int = value;
3754
3755         if (!drv->bss.beacon_set)
3756                 return 0;
3757
3758         msg = nlmsg_alloc();
3759         if (!msg)
3760                 return -ENOMEM;
3761
3762         wpa_printf(MSG_DEBUG, "nl80211: Set beacon interval %d "
3763                    "(beacon_set=%d)", value, drv->bss.beacon_set);
3764         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3765                     0, NL80211_CMD_SET_BEACON, 0);
3766         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3767
3768         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, value);
3769
3770         return send_and_recv_msgs(drv, msg, NULL, NULL);
3771  nla_put_failure:
3772         return -ENOBUFS;
3773 }
3774
3775
3776 static int i802_set_bss(void *priv, int cts, int preamble, int slot)
3777 {
3778         struct wpa_driver_nl80211_data *drv = priv;
3779         struct nl_msg *msg;
3780
3781         msg = nlmsg_alloc();
3782         if (!msg)
3783                 return -ENOMEM;
3784
3785         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3786                     NL80211_CMD_SET_BSS, 0);
3787
3788         if (cts >= 0)
3789                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
3790         if (preamble >= 0)
3791                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
3792         if (slot >= 0)
3793                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
3794
3795         /* TODO: multi-BSS support */
3796         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
3797
3798         return send_and_recv_msgs(drv, msg, NULL, NULL);
3799  nla_put_failure:
3800         return -ENOBUFS;
3801 }
3802
3803
3804 static int i802_set_cts_protect(void *priv, int value)
3805 {
3806         return i802_set_bss(priv, value, -1, -1);
3807 }
3808
3809
3810 static int i802_set_preamble(void *priv, int value)
3811 {
3812         return i802_set_bss(priv, -1, value, -1);
3813 }
3814
3815
3816 static int i802_set_short_slot_time(void *priv, int value)
3817 {
3818         return i802_set_bss(priv, -1, -1, value);
3819 }
3820
3821
3822 static enum nl80211_iftype i802_if_type(enum hostapd_driver_if_type type)
3823 {
3824         switch (type) {
3825         case HOSTAPD_IF_VLAN:
3826                 return NL80211_IFTYPE_AP_VLAN;
3827         case HOSTAPD_IF_WDS:
3828                 return NL80211_IFTYPE_WDS;
3829         }
3830         return -1;
3831 }
3832
3833
3834 static int i802_if_add(const char *iface, void *priv,
3835                        enum hostapd_driver_if_type type, char *ifname,
3836                        const u8 *addr)
3837 {
3838         if (nl80211_create_iface(priv, ifname, i802_if_type(type), addr) < 0)
3839                 return -1;
3840         return 0;
3841 }
3842
3843
3844 static int i802_if_update(void *priv, enum hostapd_driver_if_type type,
3845                           char *ifname, const u8 *addr)
3846 {
3847         /* unused at the moment */
3848         return -1;
3849 }
3850
3851
3852 static int i802_if_remove(void *priv, enum hostapd_driver_if_type type,
3853                           const char *ifname, const u8 *addr)
3854 {
3855         nl80211_remove_iface(priv, if_nametoindex(ifname));
3856         return 0;
3857 }
3858
3859
3860 static int i802_set_sta_vlan(void *priv, const u8 *addr,
3861                              const char *ifname, int vlan_id)
3862 {
3863         struct wpa_driver_nl80211_data *drv = priv;
3864         struct nl_msg *msg;
3865
3866         msg = nlmsg_alloc();
3867         if (!msg)
3868                 return -ENOMEM;
3869
3870         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3871                     0, NL80211_CMD_SET_STATION, 0);
3872
3873         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3874                     if_nametoindex(drv->ifname));
3875         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3876         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3877                     if_nametoindex(ifname));
3878
3879         return send_and_recv_msgs(drv, msg, NULL, NULL);
3880  nla_put_failure:
3881         return -ENOBUFS;
3882 }
3883
3884
3885 static int i802_set_country(void *priv, const char *country)
3886 {
3887         struct wpa_driver_nl80211_data *drv = priv;
3888         struct nl_msg *msg;
3889         char alpha2[3];
3890
3891         msg = nlmsg_alloc();
3892         if (!msg)
3893                 return -ENOMEM;
3894
3895         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3896                     0, NL80211_CMD_REQ_SET_REG, 0);
3897
3898         alpha2[0] = country[0];
3899         alpha2[1] = country[1];
3900         alpha2[2] = '\0';
3901         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
3902
3903         return send_and_recv_msgs(drv, msg, NULL, NULL);
3904  nla_put_failure:
3905         return -ENOBUFS;
3906 }
3907
3908
3909 static void handle_tx_callback(struct hostapd_data *hapd, u8 *buf, size_t len,
3910                                int ok)
3911 {
3912         struct ieee80211_hdr *hdr;
3913         u16 fc, type, stype;
3914
3915         hdr = (struct ieee80211_hdr *) buf;
3916         fc = le_to_host16(hdr->frame_control);
3917
3918         type = WLAN_FC_GET_TYPE(fc);
3919         stype = WLAN_FC_GET_STYPE(fc);
3920
3921         switch (type) {
3922         case WLAN_FC_TYPE_MGMT:
3923                 wpa_printf(MSG_DEBUG, "MGMT (TX callback) %s",
3924                            ok ? "ACK" : "fail");
3925                 hostapd_mgmt_tx_cb(hapd, buf, len, stype, ok);
3926                 break;
3927         case WLAN_FC_TYPE_CTRL:
3928                 wpa_printf(MSG_DEBUG, "CTRL (TX callback) %s",
3929                            ok ? "ACK" : "fail");
3930                 break;
3931         case WLAN_FC_TYPE_DATA:
3932                 hostapd_tx_status(hapd, hdr->addr1, buf, len, ok);
3933                 break;
3934         default:
3935                 printf("unknown TX callback frame type %d\n", type);
3936                 break;
3937         }
3938 }
3939
3940
3941 static void handle_frame(struct wpa_driver_nl80211_data *drv,
3942                          struct hostapd_iface *iface, u8 *buf, size_t len,
3943                          struct hostapd_frame_info *hfi,
3944                          enum ieee80211_msg_type msg_type)
3945 {
3946         struct ieee80211_hdr *hdr;
3947         u16 fc, type, stype;
3948         size_t data_len = len;
3949         struct hostapd_data *hapd = NULL;
3950         int broadcast_bssid = 0;
3951         size_t i;
3952         u8 *bssid;
3953
3954         /*
3955          * PS-Poll frames are 16 bytes. All other frames are
3956          * 24 bytes or longer.
3957          */
3958         if (len < 16)
3959                 return;
3960
3961         hdr = (struct ieee80211_hdr *) buf;
3962         fc = le_to_host16(hdr->frame_control);
3963
3964         type = WLAN_FC_GET_TYPE(fc);
3965         stype = WLAN_FC_GET_STYPE(fc);
3966
3967         switch (type) {
3968         case WLAN_FC_TYPE_DATA:
3969                 if (len < 24)
3970                         return;
3971                 switch (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) {
3972                 case WLAN_FC_TODS:
3973                         bssid = hdr->addr1;
3974                         break;
3975                 case WLAN_FC_FROMDS:
3976                         bssid = hdr->addr2;
3977                         break;
3978                 default:
3979                         /* discard */
3980                         return;
3981                 }
3982                 break;
3983         case WLAN_FC_TYPE_CTRL:
3984                 /* discard non-ps-poll frames */
3985                 if (stype != WLAN_FC_STYPE_PSPOLL)
3986                         return;
3987                 bssid = hdr->addr1;
3988                 break;
3989         case WLAN_FC_TYPE_MGMT:
3990                 bssid = hdr->addr3;
3991                 break;
3992         default:
3993                 /* discard */
3994                 return;
3995         }
3996
3997         /* find interface frame belongs to */
3998         for (i = 0; i < iface->num_bss; i++) {
3999                 if (memcmp(bssid, iface->bss[i]->own_addr, ETH_ALEN) == 0) {
4000                         hapd = iface->bss[i];
4001                         break;
4002                 }
4003         }
4004
4005         if (hapd == NULL) {
4006                 hapd = iface->bss[0];
4007
4008                 if (bssid[0] != 0xff || bssid[1] != 0xff ||
4009                     bssid[2] != 0xff || bssid[3] != 0xff ||
4010                     bssid[4] != 0xff || bssid[5] != 0xff) {
4011                         /*
4012                          * Unknown BSSID - drop frame if this is not from
4013                          * passive scanning or a beacon (at least ProbeReq
4014                          * frames to other APs may be allowed through RX
4015                          * filtering in the wlan hw/driver)
4016                          */
4017                         if ((type != WLAN_FC_TYPE_MGMT ||
4018                              stype != WLAN_FC_STYPE_BEACON))
4019                                 return;
4020                 } else
4021                         broadcast_bssid = 1;
4022         }
4023
4024         switch (msg_type) {
4025         case ieee80211_msg_normal:
4026                 /* continue processing */
4027                 break;
4028         case ieee80211_msg_tx_callback_ack:
4029                 handle_tx_callback(hapd, buf, data_len, 1);
4030                 return;
4031         case ieee80211_msg_tx_callback_fail:
4032                 handle_tx_callback(hapd, buf, data_len, 0);
4033                 return;
4034         }
4035
4036         switch (type) {
4037         case WLAN_FC_TYPE_MGMT:
4038                 if (stype != WLAN_FC_STYPE_BEACON &&
4039                     stype != WLAN_FC_STYPE_PROBE_REQ)
4040                         wpa_printf(MSG_MSGDUMP, "MGMT");
4041                 if (broadcast_bssid) {
4042                         for (i = 0; i < iface->num_bss; i++)
4043                                 hostapd_mgmt_rx(iface->bss[i], buf, data_len,
4044                                                 stype, hfi);
4045                 } else
4046                         hostapd_mgmt_rx(hapd, buf, data_len, stype, hfi);
4047                 break;
4048         case WLAN_FC_TYPE_CTRL:
4049                 /* can only get here with PS-Poll frames */
4050                 wpa_printf(MSG_DEBUG, "CTRL");
4051                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
4052                 break;
4053         case WLAN_FC_TYPE_DATA:
4054                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
4055                 break;
4056         }
4057 }
4058
4059
4060 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
4061 {
4062         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4063         struct sockaddr_ll lladdr;
4064         unsigned char buf[3000];
4065         int len;
4066         socklen_t fromlen = sizeof(lladdr);
4067
4068         len = recvfrom(sock, buf, sizeof(buf), 0,
4069                        (struct sockaddr *)&lladdr, &fromlen);
4070         if (len < 0) {
4071                 perror("recv");
4072                 return;
4073         }
4074
4075         if (have_ifidx(drv, lladdr.sll_ifindex)) {
4076                 struct hostapd_data *hapd;
4077                 hapd = hostapd_sta_get_bss(drv->hapd, lladdr.sll_addr);
4078                 if (!hapd)
4079                         return;
4080                 hostapd_eapol_receive(hapd, lladdr.sll_addr, buf, len);
4081         }
4082 }
4083
4084
4085 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
4086 {
4087         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4088         int len;
4089         unsigned char buf[3000];
4090         struct hostapd_data *hapd = drv->hapd;
4091         struct ieee80211_radiotap_iterator iter;
4092         int ret;
4093         struct hostapd_frame_info hfi;
4094         int injected = 0, failed = 0, msg_type, rxflags = 0;
4095
4096         len = recv(sock, buf, sizeof(buf), 0);
4097         if (len < 0) {
4098                 perror("recv");
4099                 return;
4100         }
4101
4102         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
4103                 printf("received invalid radiotap frame\n");
4104                 return;
4105         }
4106
4107         memset(&hfi, 0, sizeof(hfi));
4108
4109         while (1) {
4110                 ret = ieee80211_radiotap_iterator_next(&iter);
4111                 if (ret == -ENOENT)
4112                         break;
4113                 if (ret) {
4114                         printf("received invalid radiotap frame (%d)\n", ret);
4115                         return;
4116                 }
4117                 switch (iter.this_arg_index) {
4118                 case IEEE80211_RADIOTAP_FLAGS:
4119                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
4120                                 len -= 4;
4121                         break;
4122                 case IEEE80211_RADIOTAP_RX_FLAGS:
4123                         rxflags = 1;
4124                         break;
4125                 case IEEE80211_RADIOTAP_TX_FLAGS:
4126                         injected = 1;
4127                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
4128                                         IEEE80211_RADIOTAP_F_TX_FAIL;
4129                         break;
4130                 case IEEE80211_RADIOTAP_DATA_RETRIES:
4131                         break;
4132                 case IEEE80211_RADIOTAP_CHANNEL:
4133                         /* TODO convert from freq/flags to channel number
4134                         hfi.channel = XXX;
4135                         hfi.phytype = XXX;
4136                          */
4137                         break;
4138                 case IEEE80211_RADIOTAP_RATE:
4139                         hfi.datarate = *iter.this_arg * 5;
4140                         break;
4141                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
4142                         hfi.ssi_signal = *iter.this_arg;
4143                         break;
4144                 }
4145         }
4146
4147         if (rxflags && injected)
4148                 return;
4149
4150         if (!injected)
4151                 msg_type = ieee80211_msg_normal;
4152         else if (failed)
4153                 msg_type = ieee80211_msg_tx_callback_fail;
4154         else
4155                 msg_type = ieee80211_msg_tx_callback_ack;
4156
4157         handle_frame(drv, hapd->iface, buf + iter.max_length,
4158                      len - iter.max_length, &hfi, msg_type);
4159 }
4160
4161
4162 /*
4163  * we post-process the filter code later and rewrite
4164  * this to the offset to the last instruction
4165  */
4166 #define PASS    0xFF
4167 #define FAIL    0xFE
4168
4169 static struct sock_filter msock_filter_insns[] = {
4170         /*
4171          * do a little-endian load of the radiotap length field
4172          */
4173         /* load lower byte into A */
4174         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
4175         /* put it into X (== index register) */
4176         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4177         /* load upper byte into A */
4178         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
4179         /* left-shift it by 8 */
4180         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
4181         /* or with X */
4182         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
4183         /* put result into X */
4184         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4185
4186         /*
4187          * Allow management frames through, this also gives us those
4188          * management frames that we sent ourselves with status
4189          */
4190         /* load the lower byte of the IEEE 802.11 frame control field */
4191         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
4192         /* mask off frame type and version */
4193         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
4194         /* accept frame if it's both 0, fall through otherwise */
4195         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
4196
4197         /*
4198          * TODO: add a bit to radiotap RX flags that indicates
4199          * that the sending station is not associated, then
4200          * add a filter here that filters on our DA and that flag
4201          * to allow us to deauth frames to that bad station.
4202          *
4203          * Not a regression -- we didn't do it before either.
4204          */
4205
4206 #if 0
4207         /*
4208          * drop non-data frames, WDS frames
4209          */
4210         /* load the lower byte of the frame control field */
4211         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4212         /* mask off QoS bit */
4213         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
4214         /* drop non-data frames */
4215         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
4216         /* load the upper byte of the frame control field */
4217         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4218         /* mask off toDS/fromDS */
4219         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
4220         /* drop WDS frames */
4221         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, FAIL, 0),
4222 #endif
4223
4224         /*
4225          * add header length to index
4226          */
4227         /* load the lower byte of the frame control field */
4228         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4229         /* mask off QoS bit */
4230         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
4231         /* right shift it by 6 to give 0 or 2 */
4232         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
4233         /* add data frame header length */
4234         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
4235         /* add index, was start of 802.11 header */
4236         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
4237         /* move to index, now start of LL header */
4238         BPF_STMT(BPF_MISC | BPF_TAX, 0),
4239
4240         /*
4241          * Accept empty data frames, we use those for
4242          * polling activity.
4243          */
4244         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
4245         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
4246
4247         /*
4248          * Accept EAPOL frames
4249          */
4250         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
4251         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
4252         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
4253         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
4254
4255         /* keep these last two statements or change the code below */
4256         /* return 0 == "DROP" */
4257         BPF_STMT(BPF_RET | BPF_K, 0),
4258         /* return ~0 == "keep all" */
4259         BPF_STMT(BPF_RET | BPF_K, ~0),
4260 };
4261
4262 static struct sock_fprog msock_filter = {
4263         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
4264         .filter = msock_filter_insns,
4265 };
4266
4267
4268 static int add_monitor_filter(int s)
4269 {
4270         int idx;
4271
4272         /* rewrite all PASS/FAIL jump offsets */
4273         for (idx = 0; idx < msock_filter.len; idx++) {
4274                 struct sock_filter *insn = &msock_filter_insns[idx];
4275
4276                 if (BPF_CLASS(insn->code) == BPF_JMP) {
4277                         if (insn->code == (BPF_JMP|BPF_JA)) {
4278                                 if (insn->k == PASS)
4279                                         insn->k = msock_filter.len - idx - 2;
4280                                 else if (insn->k == FAIL)
4281                                         insn->k = msock_filter.len - idx - 3;
4282                         }
4283
4284                         if (insn->jt == PASS)
4285                                 insn->jt = msock_filter.len - idx - 2;
4286                         else if (insn->jt == FAIL)
4287                                 insn->jt = msock_filter.len - idx - 3;
4288
4289                         if (insn->jf == PASS)
4290                                 insn->jf = msock_filter.len - idx - 2;
4291                         else if (insn->jf == FAIL)
4292                                 insn->jf = msock_filter.len - idx - 3;
4293                 }
4294         }
4295
4296         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
4297                        &msock_filter, sizeof(msock_filter))) {
4298                 perror("SO_ATTACH_FILTER");
4299                 return -1;
4300         }
4301
4302         return 0;
4303 }
4304
4305
4306 static int nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
4307 {
4308         char buf[IFNAMSIZ];
4309         struct sockaddr_ll ll;
4310         int optval;
4311         socklen_t optlen;
4312
4313         snprintf(buf, IFNAMSIZ, "mon.%s", drv->ifname);
4314         buf[IFNAMSIZ - 1] = '\0';
4315
4316         drv->monitor_ifidx =
4317                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL);
4318
4319         if (drv->monitor_ifidx < 0)
4320                 return -1;
4321
4322         if (hostapd_set_iface_flags(drv, buf, 1))
4323                 goto error;
4324
4325         memset(&ll, 0, sizeof(ll));
4326         ll.sll_family = AF_PACKET;
4327         ll.sll_ifindex = drv->monitor_ifidx;
4328         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
4329         if (drv->monitor_sock < 0) {
4330                 perror("socket[PF_PACKET,SOCK_RAW]");
4331                 goto error;
4332         }
4333
4334         if (add_monitor_filter(drv->monitor_sock)) {
4335                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
4336                            "interface; do filtering in user space");
4337                 /* This works, but will cost in performance. */
4338         }
4339
4340         if (bind(drv->monitor_sock, (struct sockaddr *) &ll,
4341                  sizeof(ll)) < 0) {
4342                 perror("monitor socket bind");
4343                 goto error;
4344         }
4345
4346         optlen = sizeof(optval);
4347         optval = 20;
4348         if (setsockopt
4349             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
4350                 perror("Failed to set socket priority");
4351                 goto error;
4352         }
4353
4354         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
4355                                      drv, NULL)) {
4356                 printf("Could not register monitor read socket\n");
4357                 goto error;
4358         }
4359
4360         return 0;
4361  error:
4362         nl80211_remove_iface(drv, drv->monitor_ifidx);
4363         return -1;
4364 }
4365
4366
4367 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv, const char *ifname,
4368                             int mode)
4369 {
4370         struct nl_msg *msg;
4371         int ret = -ENOBUFS;
4372
4373         msg = nlmsg_alloc();
4374         if (!msg)
4375                 return -ENOMEM;
4376
4377         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4378                     0, NL80211_CMD_SET_INTERFACE, 0);
4379         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4380                     if_nametoindex(ifname));
4381         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
4382
4383         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4384         if (!ret)
4385                 return 0;
4386  nla_put_failure:
4387         wpa_printf(MSG_ERROR, "Failed to set interface %s to master "
4388                    "mode.", ifname);
4389         return ret;
4390 }
4391
4392
4393 #ifdef CONFIG_IEEE80211N
4394 static void i802_add_neighbor(struct wpa_driver_nl80211_data *drv, u8 *bssid,
4395                               int freq, u8 *ie, size_t ie_len)
4396 {
4397         struct ieee802_11_elems elems;
4398         int ht, pri_chan = 0, sec_chan = 0;
4399         struct ieee80211_ht_operation *oper;
4400         struct hostapd_neighbor_bss *nnei;
4401
4402         ieee802_11_parse_elems(ie, ie_len, &elems, 0);
4403         ht = elems.ht_capabilities || elems.ht_operation;
4404         if (elems.ht_operation && elems.ht_operation_len >= sizeof(*oper)) {
4405                 oper = (struct ieee80211_ht_operation *) elems.ht_operation;
4406                 pri_chan = oper->control_chan;
4407                 if (oper->ht_param & HT_INFO_HT_PARAM_REC_TRANS_CHNL_WIDTH) {
4408                         if (oper->ht_param &
4409                             HT_INFO_HT_PARAM_SECONDARY_CHNL_ABOVE)
4410                                 sec_chan = pri_chan + 4;
4411                         else if (oper->ht_param &
4412                             HT_INFO_HT_PARAM_SECONDARY_CHNL_BELOW)
4413                                 sec_chan = pri_chan - 4;
4414                 }
4415         }
4416
4417         wpa_printf(MSG_DEBUG, "nl80211: Neighboring BSS - bssid=" MACSTR
4418                    " freq=%d MHz HT=%d pri_chan=%d sec_chan=%d",
4419                    MAC2STR(bssid), freq, ht, pri_chan, sec_chan);
4420
4421         nnei = os_realloc(drv->neighbors, (drv->num_neighbors + 1) *
4422                           sizeof(struct hostapd_neighbor_bss));
4423         if (nnei == NULL)
4424                 return;
4425         drv->neighbors = nnei;
4426         nnei = &nnei[drv->num_neighbors];
4427         os_memcpy(nnei->bssid, bssid, ETH_ALEN);
4428         nnei->freq = freq;
4429         nnei->ht = !!ht;
4430         nnei->pri_chan = pri_chan;
4431         nnei->sec_chan = sec_chan;
4432         drv->num_neighbors++;
4433 }
4434
4435
4436 static int i802_get_scan_freq(struct iw_event *iwe, int *freq)
4437 {
4438         int divi = 1000000, i;
4439
4440         if (iwe->u.freq.e == 0) {
4441                 /*
4442                  * Some drivers do not report frequency, but a channel.
4443                  * Try to map this to frequency by assuming they are using
4444                  * IEEE 802.11b/g.  But don't overwrite a previously parsed
4445                  * frequency if the driver sends both frequency and channel,
4446                  * since the driver may be sending an A-band channel that we
4447                  * don't handle here.
4448                  */
4449
4450                 if (*freq)
4451                         return 0;
4452
4453                 if (iwe->u.freq.m >= 1 && iwe->u.freq.m <= 13) {
4454                         *freq = 2407 + 5 * iwe->u.freq.m;
4455                         return 0;
4456                 } else if (iwe->u.freq.m == 14) {
4457                         *freq = 2484;
4458                         return 0;
4459                 }
4460         }
4461
4462         if (iwe->u.freq.e > 6) {
4463                 wpa_printf(MSG_DEBUG, "Invalid freq in scan results: "
4464                            "m=%d e=%d", iwe->u.freq.m, iwe->u.freq.e);
4465                 return -1;
4466         }
4467
4468         for (i = 0; i < iwe->u.freq.e; i++)
4469                 divi /= 10;
4470         *freq = iwe->u.freq.m / divi;
4471         return 0;
4472 }
4473
4474
4475 static int i802_parse_scan(struct wpa_driver_nl80211_data *drv, u8 *res_buf,
4476                            size_t len)
4477 {
4478         size_t ap_num = 0;
4479         int first;
4480         struct iw_event iwe_buf, *iwe = &iwe_buf;
4481         char *pos, *end, *custom;
4482         u8 bssid[ETH_ALEN];
4483         int freq = 0;
4484         u8 *ie = NULL;
4485         size_t ie_len = 0;
4486
4487         ap_num = 0;
4488         first = 1;
4489
4490         pos = (char *) res_buf;
4491         end = (char *) res_buf + len;
4492
4493         while (pos + IW_EV_LCP_LEN <= end) {
4494                 /* Event data may be unaligned, so make a local, aligned copy
4495                  * before processing. */
4496                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
4497                 if (iwe->len <= IW_EV_LCP_LEN)
4498                         break;
4499
4500                 custom = pos + IW_EV_POINT_LEN;
4501                 if (iwe->cmd == IWEVGENIE) {
4502                         /* WE-19 removed the pointer from struct iw_point */
4503                         char *dpos = (char *) &iwe_buf.u.data.length;
4504                         int dlen = dpos - (char *) &iwe_buf;
4505                         os_memcpy(dpos, pos + IW_EV_LCP_LEN,
4506                                   sizeof(struct iw_event) - dlen);
4507                 } else {
4508                         os_memcpy(&iwe_buf, pos, sizeof(struct iw_event));
4509                         custom += IW_EV_POINT_OFF;
4510                 }
4511
4512                 switch (iwe->cmd) {
4513                 case SIOCGIWAP:
4514                         if (!first)
4515                                 i802_add_neighbor(drv, bssid, freq, ie,
4516                                                   ie_len);
4517                         first = 0;
4518                         os_memcpy(bssid, iwe->u.ap_addr.sa_data, ETH_ALEN);
4519                         freq = 0;
4520                         ie = NULL;
4521                         ie_len = 0;
4522                         break;
4523                 case SIOCGIWFREQ:
4524                         i802_get_scan_freq(iwe, &freq);
4525                         break;
4526                 case IWEVGENIE:
4527                         if (custom + iwe->u.data.length > end) {
4528                                 wpa_printf(MSG_ERROR, "IWEVGENIE overflow");
4529                                 return -1;
4530                         }
4531                         ie = (u8 *) custom;
4532                         ie_len = iwe->u.data.length;
4533                         break;
4534                 }
4535
4536                 pos += iwe->len;
4537         }
4538
4539         if (!first)
4540                 i802_add_neighbor(drv, bssid, freq, ie, ie_len);
4541
4542         return 0;
4543 }
4544
4545
4546 static int i802_get_ht_scan_res(struct wpa_driver_nl80211_data *drv)
4547 {
4548         struct iwreq iwr;
4549         u8 *res_buf;
4550         size_t res_buf_len;
4551         int res;
4552
4553         res_buf_len = IW_SCAN_MAX_DATA;
4554         for (;;) {
4555                 res_buf = os_malloc(res_buf_len);
4556                 if (res_buf == NULL)
4557                         return -1;
4558                 os_memset(&iwr, 0, sizeof(iwr));
4559                 os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
4560                 iwr.u.data.pointer = res_buf;
4561                 iwr.u.data.length = res_buf_len;
4562
4563                 if (ioctl(drv->ioctl_sock, SIOCGIWSCAN, &iwr) == 0)
4564                         break;
4565
4566                 if (errno == E2BIG && res_buf_len < 65535) {
4567                         os_free(res_buf);
4568                         res_buf = NULL;
4569                         res_buf_len *= 2;
4570                         if (res_buf_len > 65535)
4571                                 res_buf_len = 65535; /* 16-bit length field */
4572                         wpa_printf(MSG_DEBUG, "Scan results did not fit - "
4573                                    "trying larger buffer (%lu bytes)",
4574                                    (unsigned long) res_buf_len);
4575                 } else {
4576                         perror("ioctl[SIOCGIWSCAN]");
4577                         os_free(res_buf);
4578                         return -1;
4579                 }
4580         }
4581
4582         if (iwr.u.data.length > res_buf_len) {
4583                 os_free(res_buf);
4584                 return -1;
4585         }
4586
4587         res = i802_parse_scan(drv, res_buf, iwr.u.data.length);
4588         os_free(res_buf);
4589
4590         return res;
4591 }
4592
4593
4594 static int i802_is_event_wireless_scan_complete(char *data, int len)
4595 {
4596         struct iw_event iwe_buf, *iwe = &iwe_buf;
4597         char *pos, *end;
4598
4599         pos = data;
4600         end = data + len;
4601
4602         while (pos + IW_EV_LCP_LEN <= end) {
4603                 /* Event data may be unaligned, so make a local, aligned copy
4604                  * before processing. */
4605                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
4606                 if (iwe->cmd == SIOCGIWSCAN)
4607                         return 1;
4608
4609                 pos += iwe->len;
4610         }
4611
4612         return 0;
4613 }
4614
4615
4616 static int i802_is_rtm_scan_complete(int ifindex, struct nlmsghdr *h, int len)
4617 {
4618         struct ifinfomsg *ifi;
4619         int attrlen, _nlmsg_len, rta_len;
4620         struct rtattr *attr;
4621
4622         if (len < (int) sizeof(*ifi))
4623                 return 0;
4624
4625         ifi = NLMSG_DATA(h);
4626
4627         if (ifindex != ifi->ifi_index)
4628                 return 0; /* event for foreign ifindex */
4629
4630         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
4631
4632         attrlen = h->nlmsg_len - _nlmsg_len;
4633         if (attrlen < 0)
4634                 return 0;
4635
4636         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
4637
4638         rta_len = RTA_ALIGN(sizeof(struct rtattr));
4639         while (RTA_OK(attr, attrlen)) {
4640                 if (attr->rta_type == IFLA_WIRELESS &&
4641                     i802_is_event_wireless_scan_complete(
4642                             ((char *) attr) + rta_len,
4643                             attr->rta_len - rta_len))
4644                         return 1;
4645                 attr = RTA_NEXT(attr, attrlen);
4646         }
4647
4648         return 0;
4649 }
4650
4651
4652 static int i802_is_scan_complete(int s, int ifindex)
4653 {
4654         char buf[1024];
4655         int left;
4656         struct nlmsghdr *h;
4657
4658         left = recv(s, buf, sizeof(buf), MSG_DONTWAIT);
4659         if (left < 0) {
4660                 perror("recv(netlink)");
4661                 return 0;
4662         }
4663
4664         h = (struct nlmsghdr *) buf;
4665         while (left >= (int) sizeof(*h)) {
4666                 int len, plen;
4667
4668                 len = h->nlmsg_len;
4669                 plen = len - sizeof(*h);
4670                 if (len > left || plen < 0) {
4671                         wpa_printf(MSG_DEBUG, "Malformed netlink message: "
4672                                    "len=%d left=%d plen=%d",
4673                                    len, left, plen);
4674                         break;
4675                 }
4676
4677                 switch (h->nlmsg_type) {
4678                 case RTM_NEWLINK:
4679                         if (i802_is_rtm_scan_complete(ifindex, h, plen))
4680                                 return 1;
4681                         break;
4682                 }
4683
4684                 len = NLMSG_ALIGN(len);
4685                 left -= len;
4686                 h = (struct nlmsghdr *) ((char *) h + len);
4687         }
4688
4689         return 0;
4690 }
4691
4692
4693 static int i802_ht_scan(struct wpa_driver_nl80211_data *drv)
4694 {
4695         struct iwreq iwr;
4696         int s, res, ifindex;
4697         struct sockaddr_nl local;
4698         time_t now, end;
4699         fd_set rfds;
4700         struct timeval tv;
4701
4702         wpa_printf(MSG_DEBUG, "nl80211: Scanning overlapping BSSes before "
4703                    "starting HT 20/40 MHz BSS");
4704
4705         /* Request a new scan */
4706         /* TODO: would be enough to scan the selected band */
4707         os_memset(&iwr, 0, sizeof(iwr));
4708         os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
4709         if (ioctl(drv->ioctl_sock, SIOCSIWSCAN, &iwr) < 0) {
4710                 perror("ioctl[SIOCSIWSCAN]");
4711                 return -1;
4712         }
4713
4714         ifindex = if_nametoindex(drv->ifname);
4715
4716         /* Wait for scan completion event or timeout */
4717         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
4718         if (s < 0) {
4719                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
4720                 return -1;
4721         }
4722
4723         os_memset(&local, 0, sizeof(local));
4724         local.nl_family = AF_NETLINK;
4725         local.nl_groups = RTMGRP_LINK;
4726         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
4727                 perror("bind(netlink)");
4728                 close(s);
4729                 return -1;
4730         }
4731
4732         time(&end);
4733         end += 30; /* Wait at most 30 seconds for scan results */
4734         for (;;) {
4735                 time(&now);
4736                 tv.tv_sec = end > now ? end - now : 0;
4737                 tv.tv_usec = 0;
4738                 FD_ZERO(&rfds);
4739                 FD_SET(s, &rfds);
4740                 res = select(s + 1, &rfds, NULL, NULL, &tv);
4741                 if (res < 0) {
4742                         perror("select");
4743                         /* Assume results are ready after 10 seconds wait */
4744                         os_sleep(10, 0);
4745                         break;
4746                 } else if (res) {
4747                         if (i802_is_scan_complete(s, ifindex)) {
4748                                 wpa_printf(MSG_DEBUG, "nl80211: Scan "
4749                                            "completed");
4750                                 break;
4751                         }
4752                 } else {
4753                         wpa_printf(MSG_DEBUG, "nl80211: Scan timeout");
4754                         /* Assume results are ready to be read now */
4755                         break;
4756                 }
4757         }
4758
4759         close(s);
4760
4761         return i802_get_ht_scan_res(drv);
4762 }
4763 #endif /* CONFIG_IEEE80211N */
4764
4765
4766 static int i802_init_sockets(struct wpa_driver_nl80211_data *drv, const u8 *bssid)
4767 {
4768         struct ifreq ifr;
4769         int ret;
4770
4771         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
4772         if (drv->ioctl_sock < 0) {
4773                 perror("socket[PF_INET,SOCK_DGRAM]");
4774                 return -1;
4775         }
4776
4777         /* start listening for EAPOL on the default AP interface */
4778         add_ifidx(drv, if_nametoindex(drv->ifname));
4779
4780         if (hostapd_set_iface_flags(drv, drv->ifname, 0))
4781                 return -1;
4782
4783         if (bssid) {
4784                 os_strlcpy(ifr.ifr_name, drv->ifname, IFNAMSIZ);
4785                 memcpy(ifr.ifr_hwaddr.sa_data, bssid, ETH_ALEN);
4786                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
4787
4788                 if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifr)) {
4789                         perror("ioctl(SIOCSIFHWADDR)");
4790                         return -1;
4791                 }
4792         }
4793
4794         /*
4795          * initialise generic netlink and nl80211
4796          */
4797         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
4798         if (!drv->nl_cb) {
4799                 printf("Failed to allocate netlink callbacks.\n");
4800                 return -1;
4801         }
4802
4803         drv->nl_handle = nl_handle_alloc_cb(drv->nl_cb);
4804         if (!drv->nl_handle) {
4805                 printf("Failed to allocate netlink handle.\n");
4806                 return -1;
4807         }
4808
4809         if (genl_connect(drv->nl_handle)) {
4810                 printf("Failed to connect to generic netlink.\n");
4811                 return -1;
4812         }
4813
4814 #ifdef CONFIG_LIBNL20
4815         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
4816                 printf("Failed to allocate generic netlink cache.\n");
4817                 return -1;
4818         }
4819 #else /* CONFIG_LIBNL20 */
4820         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
4821         if (!drv->nl_cache) {
4822                 printf("Failed to allocate generic netlink cache.\n");
4823                 return -1;
4824         }
4825 #endif /* CONFIG_LIBNL20 */
4826
4827         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
4828         if (!drv->nl80211) {
4829                 printf("nl80211 not found.\n");
4830                 return -1;
4831         }
4832
4833         ret = nl_get_multicast_id(drv, "nl80211", "scan");
4834         if (ret >= 0)
4835                 ret = nl_socket_add_membership(drv->nl_handle, ret);
4836         if (ret < 0) {
4837                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
4838                            "membership for scan events: %d (%s)",
4839                            ret, strerror(-ret));
4840         }
4841
4842         ret = nl_get_multicast_id(drv, "nl80211", "mlme");
4843         if (ret >= 0)
4844                 ret = nl_socket_add_membership(drv->nl_handle, ret);
4845         if (ret < 0) {
4846                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
4847                            "membership for mlme events: %d (%s)",
4848                            ret, strerror(-ret));
4849         }
4850
4851         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle),
4852                                  wpa_driver_nl80211_event_receive, drv,
4853                                  drv->hapd);
4854
4855 #ifdef CONFIG_IEEE80211N
4856         if (drv->ht_40mhz_scan) {
4857                 if (nl80211_set_mode(drv, drv->ifname, NL80211_IFTYPE_STATION)
4858                     || hostapd_set_iface_flags(drv, drv->ifname, 1) ||
4859                     i802_ht_scan(drv) ||
4860                     hostapd_set_iface_flags(drv, drv->ifname, 0)) {
4861                         wpa_printf(MSG_ERROR, "Failed to scan channels for "
4862                                    "HT 40 MHz operations");
4863                         return -1;
4864                 }
4865         }
4866 #endif /* CONFIG_IEEE80211N */
4867
4868         /* Initialise a monitor interface */
4869         if (nl80211_create_monitor_interface(drv))
4870                 return -1;
4871
4872         if (nl80211_set_mode(drv, drv->ifname, NL80211_IFTYPE_AP))
4873                 goto fail1;
4874
4875         if (hostapd_set_iface_flags(drv, drv->ifname, 1))
4876                 goto fail1;
4877
4878         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
4879         if (drv->eapol_sock < 0) {
4880                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
4881                 goto fail1;
4882         }
4883
4884         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
4885         {
4886                 printf("Could not register read socket for eapol\n");
4887                 return -1;
4888         }
4889
4890         memset(&ifr, 0, sizeof(ifr));
4891         os_strlcpy(ifr.ifr_name, drv->ifname, sizeof(ifr.ifr_name));
4892         if (ioctl(drv->ioctl_sock, SIOCGIFHWADDR, &ifr) != 0) {
4893                 perror("ioctl(SIOCGIFHWADDR)");
4894                 goto fail1;
4895         }
4896
4897         if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
4898                 printf("Invalid HW-addr family 0x%04x\n",
4899                        ifr.ifr_hwaddr.sa_family);
4900                 goto fail1;
4901         }
4902         memcpy(drv->hapd->own_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
4903
4904         return 0;
4905
4906 fail1:
4907         nl80211_remove_iface(drv, drv->monitor_ifidx);
4908         return -1;
4909 }
4910
4911
4912 static int i802_get_inact_sec(void *priv, const u8 *addr)
4913 {
4914         struct hostap_sta_driver_data data;
4915         int ret;
4916
4917         data.inactive_msec = (unsigned long) -1;
4918         ret = i802_read_sta_data(priv, &data, addr);
4919         if (ret || data.inactive_msec == (unsigned long) -1)
4920                 return -1;
4921         return data.inactive_msec / 1000;
4922 }
4923
4924
4925 static int i802_sta_clear_stats(void *priv, const u8 *addr)
4926 {
4927 #if 0
4928         /* TODO */
4929 #endif
4930         return 0;
4931 }
4932
4933
4934 static int i802_sta_deauth(void *priv, const u8 *addr, int reason)
4935 {
4936         struct wpa_driver_nl80211_data *drv = priv;
4937         struct ieee80211_mgmt mgmt;
4938
4939         memset(&mgmt, 0, sizeof(mgmt));
4940         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
4941                                           WLAN_FC_STYPE_DEAUTH);
4942         memcpy(mgmt.da, addr, ETH_ALEN);
4943         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
4944         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
4945         mgmt.u.deauth.reason_code = host_to_le16(reason);
4946         return i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
4947                                     sizeof(mgmt.u.deauth));
4948 }
4949
4950
4951 static int i802_sta_disassoc(void *priv, const u8 *addr, int reason)
4952 {
4953         struct wpa_driver_nl80211_data *drv = priv;
4954         struct ieee80211_mgmt mgmt;
4955
4956         memset(&mgmt, 0, sizeof(mgmt));
4957         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
4958                                           WLAN_FC_STYPE_DISASSOC);
4959         memcpy(mgmt.da, addr, ETH_ALEN);
4960         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
4961         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
4962         mgmt.u.disassoc.reason_code = host_to_le16(reason);
4963         return i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
4964                                     sizeof(mgmt.u.disassoc));
4965 }
4966
4967
4968 static const struct hostapd_neighbor_bss *
4969 i802_get_neighbor_bss(void *priv, size_t *num)
4970 {
4971         struct wpa_driver_nl80211_data *drv = priv;
4972         *num = drv->num_neighbors;
4973         return drv->neighbors;
4974 }
4975
4976
4977 static void *i802_init_bssid(struct hostapd_data *hapd, const u8 *bssid)
4978 {
4979         struct wpa_driver_nl80211_data *drv;
4980         size_t i;
4981
4982         drv = os_zalloc(sizeof(struct wpa_driver_nl80211_data));
4983         if (drv == NULL) {
4984                 printf("Could not allocate memory for i802 driver data\n");
4985                 return NULL;
4986         }
4987
4988         drv->hapd = hapd;
4989         memcpy(drv->ifname, hapd->conf->iface, sizeof(drv->ifname));
4990         memcpy(drv->bss.ifname, hapd->conf->iface, sizeof(drv->bss.ifname));
4991         drv->ifindex = if_nametoindex(drv->ifname);
4992
4993         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
4994         drv->if_indices = drv->default_if_indices;
4995         for (i = 0; i < hapd->iface->num_bss; i++) {
4996                 struct hostapd_data *bss = hapd->iface->bss[i];
4997                 if (bss->conf->bridge)
4998                         add_ifidx(drv, if_nametoindex(bss->conf->bridge));
4999         }
5000         drv->ht_40mhz_scan = hapd->iconf->secondary_channel != 0;
5001
5002         if (i802_init_sockets(drv, bssid))
5003                 goto failed;
5004
5005         return drv;
5006
5007 failed:
5008         free(drv);
5009         return NULL;
5010 }
5011
5012
5013 static void *i802_init(struct hostapd_data *hapd)
5014 {
5015         return i802_init_bssid(hapd, NULL);
5016 }
5017
5018
5019 static void i802_deinit(void *priv)
5020 {
5021         struct wpa_driver_nl80211_data *drv = priv;
5022         struct i802_bss *bss, *prev;
5023
5024         if (drv->last_freq_ht) {
5025                 /* Clear HT flags from the driver */
5026                 struct hostapd_freq_params freq;
5027                 os_memset(&freq, 0, sizeof(freq));
5028                 freq.freq = drv->last_freq;
5029                 i802_set_freq(priv, &freq);
5030         }
5031
5032         i802_del_beacon(drv);
5033
5034         /* remove monitor interface */
5035         nl80211_remove_iface(drv, drv->monitor_ifidx);
5036
5037         (void) hostapd_set_iface_flags(drv, drv->ifname, 0);
5038
5039         if (drv->monitor_sock >= 0) {
5040                 eloop_unregister_read_sock(drv->monitor_sock);
5041                 close(drv->monitor_sock);
5042         }
5043         if (drv->ioctl_sock >= 0)
5044                 close(drv->ioctl_sock);
5045         if (drv->eapol_sock >= 0) {
5046                 eloop_unregister_read_sock(drv->eapol_sock);
5047                 close(drv->eapol_sock);
5048         }
5049
5050         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle));
5051         genl_family_put(drv->nl80211);
5052         nl_cache_free(drv->nl_cache);
5053         nl_handle_destroy(drv->nl_handle);
5054         nl_cb_put(drv->nl_cb);
5055
5056         if (drv->if_indices != drv->default_if_indices)
5057                 free(drv->if_indices);
5058
5059         os_free(drv->neighbors);
5060
5061         bss = drv->bss.next;
5062         while (bss) {
5063                 prev = bss;
5064                 bss = bss->next;
5065                 os_free(bss);
5066         }
5067
5068         free(drv);
5069 }
5070
5071 #endif /* HOSTAPD */
5072
5073
5074 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
5075         .name = "nl80211",
5076         .desc = "Linux nl80211/cfg80211",
5077         .get_bssid = wpa_driver_nl80211_get_bssid,
5078         .get_ssid = wpa_driver_nl80211_get_ssid,
5079         .set_key = wpa_driver_nl80211_set_key,
5080         .scan2 = wpa_driver_nl80211_scan,
5081         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
5082         .deauthenticate = wpa_driver_nl80211_deauthenticate,
5083         .disassociate = wpa_driver_nl80211_disassociate,
5084         .authenticate = wpa_driver_nl80211_authenticate,
5085         .associate = wpa_driver_nl80211_associate,
5086         .init = wpa_driver_nl80211_init,
5087         .deinit = wpa_driver_nl80211_deinit,
5088         .get_capa = wpa_driver_nl80211_get_capa,
5089         .set_operstate = wpa_driver_nl80211_set_operstate,
5090         .set_country = wpa_driver_nl80211_set_country,
5091 #ifdef CONFIG_AP
5092         .set_beacon = wpa_driver_nl80211_set_beacon,
5093         .set_beacon_int = wpa_driver_nl80211_set_beacon_int,
5094         .send_mlme = wpa_driver_nl80211_send_mlme,
5095 #endif /* CONFIG_AP */
5096 #if defined(CONFIG_AP) || defined(HOSTAPD)
5097         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
5098 #endif /* CONFIG_AP || HOSTAPD */
5099 #ifdef HOSTAPD
5100         .hapd_init = i802_init,
5101         .init_bssid = i802_init_bssid,
5102         .hapd_deinit = i802_deinit,
5103         .hapd_set_key = i802_set_key,
5104         .get_seqnum = i802_get_seqnum,
5105         .flush = i802_flush,
5106         .read_sta_data = i802_read_sta_data,
5107         .hapd_send_eapol = i802_send_eapol,
5108         .sta_set_flags = i802_sta_set_flags,
5109         .sta_deauth = i802_sta_deauth,
5110         .sta_disassoc = i802_sta_disassoc,
5111         .sta_remove = i802_sta_remove,
5112         .send_mgmt_frame = i802_send_mgmt_frame,
5113         .sta_add = i802_sta_add,
5114         .get_inact_sec = i802_get_inact_sec,
5115         .sta_clear_stats = i802_sta_clear_stats,
5116         .set_freq = i802_set_freq,
5117         .set_rts = i802_set_rts,
5118         .set_frag = i802_set_frag,
5119         .set_retry = i802_set_retry,
5120         .set_rate_sets = i802_set_rate_sets,
5121         .hapd_set_beacon = i802_set_beacon,
5122         .hapd_set_beacon_int = i802_set_beacon_int,
5123         .set_cts_protect = i802_set_cts_protect,
5124         .set_preamble = i802_set_preamble,
5125         .set_short_slot_time = i802_set_short_slot_time,
5126         .set_tx_queue_params = i802_set_tx_queue_params,
5127         .bss_add = i802_bss_add,
5128         .bss_remove = i802_bss_remove,
5129         .if_add = i802_if_add,
5130         .if_update = i802_if_update,
5131         .if_remove = i802_if_remove,
5132         .set_sta_vlan = i802_set_sta_vlan,
5133         .hapd_set_country = i802_set_country,
5134         .get_neighbor_bss = i802_get_neighbor_bss,
5135 #endif /* HOSTAPD */
5136 };