Mark STA authorized if IEEE 802.1X and WPA is not used
[wpasupplicant] / hostapd / driver_nl80211.c
1 /*
2  * hostapd / Kernel driver communication via nl80211
3  * Copyright (c) 2002-2007, Jouni Malinen <j@w1.fi>
4  * Copyright (c) 2003-2004, Instant802 Networks, Inc.
5  * Copyright (c) 2005-2006, Devicescape Software, Inc.
6  * Copyright (c) 2007, Johannes Berg <johannes@sipsolutions.net>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  *
12  * Alternatively, this software may be distributed under the terms of BSD
13  * license.
14  *
15  * See README and COPYING for more details.
16  */
17
18 #include "includes.h"
19
20 #include <sys/ioctl.h>
21 #include <netlink/genl/genl.h>
22 #include <netlink/genl/family.h>
23 #include <netlink/genl/ctrl.h>
24 #include <netlink/msg.h>
25 #include <netlink/attr.h>
26 #include "nl80211_copy.h"
27 #include <net/if.h>
28 #include <netpacket/packet.h>
29 #include "wireless_copy.h"
30 #include <linux/filter.h>
31 #include <net/if_arp.h>
32
33 #include "hostapd.h"
34 #include "config.h"
35 #include "driver.h"
36 #include "eloop.h"
37 #include "hw_features.h"
38 #include "mlme.h"
39 #include "radiotap.h"
40 #include "radiotap_iter.h"
41 #include "ieee802_11_defs.h"
42 #include "ieee802_11_common.h"
43
44 #ifdef CONFIG_LIBNL20
45 /* libnl 2.0 compatibility code */
46 #define nl_handle_alloc_cb nl_socket_alloc_cb
47 #define nl_handle_destroy nl_socket_free
48 #endif /* CONFIG_LIBNL20 */
49
50 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
51
52 enum ieee80211_msg_type {
53         ieee80211_msg_normal = 0,
54         ieee80211_msg_tx_callback_ack = 1,
55         ieee80211_msg_tx_callback_fail = 2,
56 };
57
58 struct i802_bss {
59         struct i802_bss *next;
60         char iface[IFNAMSIZ + 1];
61         unsigned int beacon_set:1;
62 };
63
64 struct i802_driver_data {
65         struct hostapd_data *hapd;
66
67         char iface[IFNAMSIZ + 1];
68         int bridge;
69         int ioctl_sock; /* socket for ioctl() use */
70         int wext_sock; /* socket for wireless events */
71         int eapol_sock; /* socket for EAPOL frames */
72         int monitor_sock; /* socket for monitor */
73         int monitor_ifidx;
74
75         int default_if_indices[16];
76         int *if_indices;
77         int num_if_indices;
78
79         int we_version;
80         struct nl_handle *nl_handle;
81         struct nl_cache *nl_cache;
82         struct nl_cb *nl_cb;
83         struct genl_family *nl80211;
84         int beacon_int;
85         struct i802_bss bss;
86         unsigned int ht_40mhz_scan:1;
87
88         int last_freq;
89         int last_freq_ht;
90         struct hostapd_neighbor_bss *neighbors;
91         size_t num_neighbors;
92 };
93
94
95 static int i802_sta_deauth(void *priv, const u8 *addr, int reason);
96 static int i802_sta_disassoc(void *priv, const u8 *addr, int reason);
97
98
99 static struct i802_bss * get_bss(struct i802_driver_data *drv,
100                                  const char *iface)
101 {
102         struct i802_bss *bss = &drv->bss;
103         while (bss) {
104                 if (os_strncmp(iface, bss->iface, IFNAMSIZ) == 0)
105                         return bss;
106                 bss = bss->next;
107         }
108         wpa_printf(MSG_DEBUG, "nl80211: get_bss(%s) failed", iface);
109         return NULL;
110 }
111
112
113 static void add_ifidx(struct i802_driver_data *drv, int ifidx)
114 {
115         int i;
116         int *old;
117
118         for (i = 0; i < drv->num_if_indices; i++) {
119                 if (drv->if_indices[i] == 0) {
120                         drv->if_indices[i] = ifidx;
121                         return;
122                 }
123         }
124
125         if (drv->if_indices != drv->default_if_indices)
126                 old = drv->if_indices;
127         else
128                 old = NULL;
129
130         drv->if_indices = realloc(old,
131                                   sizeof(int) * (drv->num_if_indices + 1));
132         if (!drv->if_indices) {
133                 if (!old)
134                         drv->if_indices = drv->default_if_indices;
135                 else
136                         drv->if_indices = old;
137                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
138                            "interfaces");
139                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
140                 return;
141         }
142         drv->if_indices[drv->num_if_indices] = ifidx;
143         drv->num_if_indices++;
144 }
145
146
147 static void del_ifidx(struct i802_driver_data *drv, int ifidx)
148 {
149         int i;
150
151         for (i = 0; i < drv->num_if_indices; i++) {
152                 if (drv->if_indices[i] == ifidx) {
153                         drv->if_indices[i] = 0;
154                         break;
155                 }
156         }
157 }
158
159
160 static int have_ifidx(struct i802_driver_data *drv, int ifidx)
161 {
162         int i;
163
164         if (ifidx == drv->bridge)
165                 return 1;
166
167         for (i = 0; i < drv->num_if_indices; i++)
168                 if (drv->if_indices[i] == ifidx)
169                         return 1;
170
171         return 0;
172 }
173
174
175 /* nl80211 code */
176 static int ack_handler(struct nl_msg *msg, void *arg)
177 {
178         int *err = arg;
179         *err = 0;
180         return NL_STOP;
181 }
182
183 static int finish_handler(struct nl_msg *msg, void *arg)
184 {
185         int *ret = arg;
186         *ret = 0;
187         return NL_SKIP;
188 }
189
190 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
191                          void *arg)
192 {
193         int *ret = arg;
194         *ret = err->error;
195         return NL_SKIP;
196 }
197
198 static int send_and_recv_msgs(struct i802_driver_data *drv,
199                               struct nl_msg *msg,
200                               int (*valid_handler)(struct nl_msg *, void *),
201                               void *valid_data)
202 {
203         struct nl_cb *cb;
204         int err = -ENOMEM;
205
206         cb = nl_cb_clone(drv->nl_cb);
207         if (!cb)
208                 goto out;
209
210         err = nl_send_auto_complete(drv->nl_handle, msg);
211         if (err < 0)
212                 goto out;
213
214         err = 1;
215
216         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
217         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
218         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
219
220         if (valid_handler)
221                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
222                           valid_handler, valid_data);
223
224         while (err > 0)
225                 nl_recvmsgs(drv->nl_handle, cb);
226  out:
227         nl_cb_put(cb);
228         nlmsg_free(msg);
229         return err;
230 }
231
232 static int hostapd_set_iface_flags(struct i802_driver_data *drv,
233                                    const char *ifname, int dev_up)
234 {
235         struct ifreq ifr;
236
237         if (drv->ioctl_sock < 0)
238                 return -1;
239
240         memset(&ifr, 0, sizeof(ifr));
241         os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
242
243         if (ioctl(drv->ioctl_sock, SIOCGIFFLAGS, &ifr) != 0) {
244                 perror("ioctl[SIOCGIFFLAGS]");
245                 wpa_printf(MSG_DEBUG, "Could not read interface flags (%s)",
246                            drv->iface);
247                 return -1;
248         }
249
250         if (dev_up)
251                 ifr.ifr_flags |= IFF_UP;
252         else
253                 ifr.ifr_flags &= ~IFF_UP;
254
255         if (ioctl(drv->ioctl_sock, SIOCSIFFLAGS, &ifr) != 0) {
256                 perror("ioctl[SIOCSIFFLAGS]");
257                 return -1;
258         }
259
260         return 0;
261 }
262
263
264 static int nl_set_encr(int ifindex, struct i802_driver_data *drv,
265                        wpa_alg alg, const u8 *addr, int idx, const u8 *key,
266                        size_t key_len, int txkey)
267 {
268         struct nl_msg *msg;
269         int ret;
270
271         msg = nlmsg_alloc();
272         if (!msg)
273                 return -ENOMEM;
274
275         if (alg == WPA_ALG_NONE) {
276                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
277                             0, NL80211_CMD_DEL_KEY, 0);
278         } else {
279                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
280                             0, NL80211_CMD_NEW_KEY, 0);
281                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
282                 switch (alg) {
283                 case WPA_ALG_WEP:
284                         if (key_len == 5)
285                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
286                                             0x000FAC01);
287                         else
288                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
289                                             0x000FAC05);
290                         break;
291                 case WPA_ALG_TKIP:
292                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC02);
293                         break;
294                 case WPA_ALG_CCMP:
295                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC04);
296                         break;
297                 case WPA_ALG_IGTK:
298                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC06);
299                         break;
300                 default:
301                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
302                                    "algorithm %d", __func__, alg);
303                         nlmsg_free(msg);
304                         return -1;
305                 }
306         }
307
308         if (addr)
309                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
310         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
311         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
312
313         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
314         if (ret == -ENOENT)
315                 ret = 0;
316
317         /*
318          * If we failed or don't need to set the default TX key (below),
319          * we're done here.
320          */
321         if (ret || !txkey || addr)
322                 return ret;
323
324         msg = nlmsg_alloc();
325         if (!msg)
326                 return -ENOMEM;
327
328         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
329                     0, NL80211_CMD_SET_KEY, 0);
330         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
331         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
332         if (alg == WPA_ALG_IGTK)
333                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
334         else
335                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
336
337         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
338         if (ret == -ENOENT)
339                 ret = 0;
340         return ret;
341  nla_put_failure:
342         return -ENOBUFS;
343 }
344
345
346 static int i802_set_key(const char *iface, void *priv, wpa_alg alg,
347                         const u8 *addr, int key_idx, int set_tx, const u8 *seq,
348                         size_t seq_len, const u8 *key, size_t key_len)
349 {
350         struct i802_driver_data *drv = priv;
351         int ret;
352
353         ret = nl_set_encr(if_nametoindex(iface), drv, alg, addr, key_idx, key,
354                           key_len, set_tx);
355         if (ret < 0)
356                 return ret;
357
358         return ret;
359 }
360
361
362 static inline int min_int(int a, int b)
363 {
364         if (a < b)
365                 return a;
366         return b;
367 }
368
369
370 static int get_key_handler(struct nl_msg *msg, void *arg)
371 {
372         struct nlattr *tb[NL80211_ATTR_MAX + 1];
373         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
374
375         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
376                   genlmsg_attrlen(gnlh, 0), NULL);
377
378         /*
379          * TODO: validate the key index and mac address!
380          * Otherwise, there's a race condition as soon as
381          * the kernel starts sending key notifications.
382          */
383
384         if (tb[NL80211_ATTR_KEY_SEQ])
385                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
386                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
387         return NL_SKIP;
388 }
389
390
391 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
392                            int idx, u8 *seq)
393 {
394         struct i802_driver_data *drv = priv;
395         struct nl_msg *msg;
396
397         msg = nlmsg_alloc();
398         if (!msg)
399                 return -ENOMEM;
400
401         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
402                     0, NL80211_CMD_GET_KEY, 0);
403
404         if (addr)
405                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
406         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
407         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
408
409         memset(seq, 0, 6);
410
411         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
412  nla_put_failure:
413         return -ENOBUFS;
414 }
415
416
417 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
418                               int mode)
419 {
420         struct i802_driver_data *drv = priv;
421         struct nl_msg *msg;
422         u8 rates[NL80211_MAX_SUPP_RATES];
423         u8 rates_len = 0;
424         int i;
425
426         msg = nlmsg_alloc();
427         if (!msg)
428                 return -ENOMEM;
429
430         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
431                     NL80211_CMD_SET_BSS, 0);
432
433         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
434                 rates[rates_len++] = basic_rates[i] / 5;
435
436         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
437
438         /* TODO: multi-BSS support */
439         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
440
441         return send_and_recv_msgs(drv, msg, NULL, NULL);
442  nla_put_failure:
443         return -ENOBUFS;
444 }
445
446
447 static int i802_send_frame(void *priv, const void *data, size_t len,
448                            int encrypt, int flags)
449 {
450         __u8 rtap_hdr[] = {
451                 0x00, 0x00, /* radiotap version */
452                 0x0e, 0x00, /* radiotap length */
453                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
454                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
455                 0x00,       /* padding */
456                 0x00, 0x00, /* RX and TX flags to indicate that */
457                 0x00, 0x00, /* this is the injected frame directly */
458         };
459         struct i802_driver_data *drv = priv;
460         struct iovec iov[2] = {
461                 {
462                         .iov_base = &rtap_hdr,
463                         .iov_len = sizeof(rtap_hdr),
464                 },
465                 {
466                         .iov_base = (void*)data,
467                         .iov_len = len,
468                 }
469         };
470         struct msghdr msg = {
471                 .msg_name = NULL,
472                 .msg_namelen = 0,
473                 .msg_iov = iov,
474                 .msg_iovlen = 2,
475                 .msg_control = NULL,
476                 .msg_controllen = 0,
477                 .msg_flags = 0,
478         };
479
480         if (encrypt)
481                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
482
483         return sendmsg(drv->monitor_sock, &msg, flags);
484 }
485
486 static int i802_send_mgmt_frame(void *priv, const void *data, size_t len,
487                                 int flags)
488 {
489         struct ieee80211_mgmt *mgmt;
490         int do_not_encrypt = 0;
491         u16 fc;
492
493         mgmt = (struct ieee80211_mgmt *) data;
494         fc = le_to_host16(mgmt->frame_control);
495
496         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
497             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
498                 /*
499                  * Only one of the authentication frame types is encrypted.
500                  * In order for static WEP encryption to work properly (i.e.,
501                  * to not encrypt the frame), we need to tell mac80211 about
502                  * the frames that must not be encrypted.
503                  */
504                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
505                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
506                 if (auth_alg == WLAN_AUTH_OPEN ||
507                     (auth_alg == WLAN_AUTH_SHARED_KEY && auth_trans != 3))
508                         do_not_encrypt = 1;
509         }
510
511         return i802_send_frame(priv, data, len, !do_not_encrypt, flags);
512 }
513
514 /* Set kernel driver on given frequency (MHz) */
515 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
516 {
517         struct i802_driver_data *drv = priv;
518         struct nl_msg *msg;
519
520         msg = nlmsg_alloc();
521         if (!msg)
522                 return -1;
523
524         drv->last_freq = freq->freq;
525         drv->last_freq_ht = freq->ht_enabled;
526
527         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
528                     NL80211_CMD_SET_WIPHY, 0);
529
530         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
531         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq->freq);
532         if (freq->ht_enabled) {
533                 switch (freq->sec_channel_offset) {
534                 case -1:
535                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
536                                     NL80211_CHAN_HT40MINUS);
537                         break;
538                 case 1:
539                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
540                                     NL80211_CHAN_HT40PLUS);
541                         break;
542                 default:
543                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
544                                     NL80211_CHAN_HT20);
545                         break;
546                 }
547         }
548
549         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
550                 return 0;
551  nla_put_failure:
552         return -1;
553 }
554
555
556 static int i802_set_rts(void *priv, int rts)
557 {
558         struct i802_driver_data *drv = priv;
559         struct iwreq iwr;
560
561         memset(&iwr, 0, sizeof(iwr));
562         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
563         iwr.u.rts.value = rts;
564         iwr.u.rts.fixed = 1;
565
566         if (ioctl(drv->ioctl_sock, SIOCSIWRTS, &iwr) < 0) {
567                 perror("ioctl[SIOCSIWRTS]");
568                 return -1;
569         }
570
571         return 0;
572 }
573
574
575 static int i802_set_frag(void *priv, int frag)
576 {
577         struct i802_driver_data *drv = priv;
578         struct iwreq iwr;
579
580         memset(&iwr, 0, sizeof(iwr));
581         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
582         iwr.u.frag.value = frag;
583         iwr.u.frag.fixed = 1;
584
585         if (ioctl(drv->ioctl_sock, SIOCSIWFRAG, &iwr) < 0) {
586                 perror("ioctl[SIOCSIWFRAG]");
587                 return -1;
588         }
589
590         return 0;
591 }
592
593
594 static int i802_set_retry(void *priv, int short_retry, int long_retry)
595 {
596         struct i802_driver_data *drv = priv;
597         struct iwreq iwr;
598
599         memset(&iwr, 0, sizeof(iwr));
600         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
601
602         iwr.u.retry.value = short_retry;
603         iwr.u.retry.flags = IW_RETRY_LIMIT | IW_RETRY_MIN;
604         if (ioctl(drv->ioctl_sock, SIOCSIWRETRY, &iwr) < 0) {
605                 perror("ioctl[SIOCSIWRETRY(short)]");
606                 return -1;
607         }
608
609         iwr.u.retry.value = long_retry;
610         iwr.u.retry.flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
611         if (ioctl(drv->ioctl_sock, SIOCSIWRETRY, &iwr) < 0) {
612                 perror("ioctl[SIOCSIWRETRY(long)]");
613                 return -1;
614         }
615
616         return 0;
617 }
618
619
620 static int i802_flush(void *priv)
621 {
622         struct i802_driver_data *drv = priv;
623         struct nl_msg *msg;
624
625         msg = nlmsg_alloc();
626         if (!msg)
627                 return -1;
628
629         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
630                     0, NL80211_CMD_DEL_STATION, 0);
631
632         /*
633          * XXX: FIX! this needs to flush all VLANs too
634          */
635         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
636                     if_nametoindex(drv->iface));
637
638         return send_and_recv_msgs(drv, msg, NULL, NULL);
639  nla_put_failure:
640         return -ENOBUFS;
641 }
642
643
644 static int get_sta_handler(struct nl_msg *msg, void *arg)
645 {
646         struct nlattr *tb[NL80211_ATTR_MAX + 1];
647         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
648         struct hostap_sta_driver_data *data = arg;
649         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
650         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
651                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
652                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
653                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
654                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
655                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
656         };
657
658         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
659                   genlmsg_attrlen(gnlh, 0), NULL);
660
661         /*
662          * TODO: validate the interface and mac address!
663          * Otherwise, there's a race condition as soon as
664          * the kernel starts sending station notifications.
665          */
666
667         if (!tb[NL80211_ATTR_STA_INFO]) {
668                 wpa_printf(MSG_DEBUG, "sta stats missing!");
669                 return NL_SKIP;
670         }
671         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
672                              tb[NL80211_ATTR_STA_INFO],
673                              stats_policy)) {
674                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
675                 return NL_SKIP;
676         }
677
678         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
679                 data->inactive_msec =
680                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
681         if (stats[NL80211_STA_INFO_RX_BYTES])
682                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
683         if (stats[NL80211_STA_INFO_TX_BYTES])
684                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
685         if (stats[NL80211_STA_INFO_RX_PACKETS])
686                 data->rx_packets =
687                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
688         if (stats[NL80211_STA_INFO_TX_PACKETS])
689                 data->tx_packets =
690                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
691
692         return NL_SKIP;
693 }
694
695 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
696                               const u8 *addr)
697 {
698         struct i802_driver_data *drv = priv;
699         struct nl_msg *msg;
700
701         os_memset(data, 0, sizeof(*data));
702         msg = nlmsg_alloc();
703         if (!msg)
704                 return -ENOMEM;
705
706         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
707                     0, NL80211_CMD_GET_STATION, 0);
708
709         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
710         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
711
712         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
713  nla_put_failure:
714         return -ENOBUFS;
715 }
716
717
718 static int i802_send_eapol(void *priv, const u8 *addr, const u8 *data,
719                            size_t data_len, int encrypt, const u8 *own_addr)
720 {
721         struct i802_driver_data *drv = priv;
722         struct ieee80211_hdr *hdr;
723         size_t len;
724         u8 *pos;
725         int res;
726 #if 0 /* FIX */
727         int qos = sta->flags & WLAN_STA_WME;
728 #else
729         int qos = 0;
730 #endif
731
732         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
733                 data_len;
734         hdr = os_zalloc(len);
735         if (hdr == NULL) {
736                 printf("malloc() failed for i802_send_data(len=%lu)\n",
737                        (unsigned long) len);
738                 return -1;
739         }
740
741         hdr->frame_control =
742                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
743         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
744         if (encrypt)
745                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
746 #if 0 /* To be enabled if qos determination is added above */
747         if (qos) {
748                 hdr->frame_control |=
749                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
750         }
751 #endif
752
753         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
754         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
755         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
756         pos = (u8 *) (hdr + 1);
757
758 #if 0 /* To be enabled if qos determination is added above */
759         if (qos) {
760                 /* add an empty QoS header if needed */
761                 pos[0] = 0;
762                 pos[1] = 0;
763                 pos += 2;
764         }
765 #endif
766
767         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
768         pos += sizeof(rfc1042_header);
769         WPA_PUT_BE16(pos, ETH_P_PAE);
770         pos += 2;
771         memcpy(pos, data, data_len);
772
773         res = i802_send_frame(drv, (u8 *) hdr, len, encrypt, 0);
774         free(hdr);
775
776         if (res < 0) {
777                 perror("i802_send_eapol: send");
778                 printf("i802_send_eapol - packet len: %lu - failed\n",
779                        (unsigned long) len);
780         }
781
782         return res;
783 }
784
785
786 static int i802_sta_add(const char *ifname, void *priv,
787                         struct hostapd_sta_add_params *params)
788 {
789         struct i802_driver_data *drv = priv;
790         struct nl_msg *msg;
791         int ret = -ENOBUFS;
792
793         msg = nlmsg_alloc();
794         if (!msg)
795                 return -ENOMEM;
796
797         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
798                     0, NL80211_CMD_NEW_STATION, 0);
799
800         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
801                     if_nametoindex(drv->iface));
802         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
803         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
804         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
805                 params->supp_rates);
806         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
807                     params->listen_interval);
808
809 #ifdef CONFIG_IEEE80211N
810         if (params->ht_capabilities) {
811                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
812                         params->ht_capabilities->length,
813                         &params->ht_capabilities->data);
814         }
815 #endif /* CONFIG_IEEE80211N */
816
817         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
818         if (ret)
819                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
820                            "result: %d (%s)", ret, strerror(-ret));
821         if (ret == -EEXIST)
822                 ret = 0;
823  nla_put_failure:
824         return ret;
825 }
826
827
828 static int i802_sta_remove(void *priv, const u8 *addr)
829 {
830         struct i802_driver_data *drv = priv;
831         struct nl_msg *msg;
832         int ret;
833
834         msg = nlmsg_alloc();
835         if (!msg)
836                 return -ENOMEM;
837
838         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
839                     0, NL80211_CMD_DEL_STATION, 0);
840
841         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
842                     if_nametoindex(drv->iface));
843         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
844
845         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
846         if (ret == -ENOENT)
847                 return 0;
848         return ret;
849  nla_put_failure:
850         return -ENOBUFS;
851 }
852
853
854 static int i802_sta_set_flags(void *priv, const u8 *addr,
855                               int total_flags, int flags_or, int flags_and)
856 {
857         struct i802_driver_data *drv = priv;
858         struct nl_msg *msg, *flags = NULL;
859
860         msg = nlmsg_alloc();
861         if (!msg)
862                 return -ENOMEM;
863
864         flags = nlmsg_alloc();
865         if (!flags) {
866                 nlmsg_free(msg);
867                 return -ENOMEM;
868         }
869
870         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
871                     0, NL80211_CMD_SET_STATION, 0);
872
873         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
874                     if_nametoindex(drv->iface));
875         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
876
877         if (total_flags & WLAN_STA_AUTHORIZED)
878                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
879
880         if (total_flags & WLAN_STA_WMM)
881                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
882
883         if (total_flags & WLAN_STA_SHORT_PREAMBLE)
884                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
885
886         if (total_flags & WLAN_STA_MFP)
887                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
888
889         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
890                 goto nla_put_failure;
891
892         nlmsg_free(flags);
893
894         return send_and_recv_msgs(drv, msg, NULL, NULL);
895  nla_put_failure:
896         nlmsg_free(flags);
897         return -ENOBUFS;
898 }
899
900
901 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
902                                     int cw_min, int cw_max, int burst_time)
903 {
904         struct i802_driver_data *drv = priv;
905         struct nl_msg *msg;
906         struct nlattr *txq, *params;
907
908         msg = nlmsg_alloc();
909         if (!msg)
910                 return -1;
911
912         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
913                     0, NL80211_CMD_SET_WIPHY, 0);
914
915         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
916
917         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
918         if (!txq)
919                 goto nla_put_failure;
920
921         /* We are only sending parameters for a single TXQ at a time */
922         params = nla_nest_start(msg, 1);
923         if (!params)
924                 goto nla_put_failure;
925
926         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, queue);
927         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
928          * 32 usec, so need to convert the value here. */
929         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
930         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
931         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
932         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
933
934         nla_nest_end(msg, params);
935
936         nla_nest_end(msg, txq);
937
938         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
939                 return 0;
940  nla_put_failure:
941         return -1;
942 }
943
944
945 static void nl80211_remove_iface(struct i802_driver_data *drv, int ifidx)
946 {
947         struct nl_msg *msg;
948
949         /* stop listening for EAPOL on this interface */
950         del_ifidx(drv, ifidx);
951
952         msg = nlmsg_alloc();
953         if (!msg)
954                 goto nla_put_failure;
955
956         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
957                     0, NL80211_CMD_DEL_INTERFACE, 0);
958         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
959
960         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
961                 return;
962  nla_put_failure:
963         printf("Failed to remove interface.\n");
964 }
965
966
967 static int nl80211_create_iface(struct i802_driver_data *drv,
968                                 const char *ifname,
969                                 enum nl80211_iftype iftype,
970                                 const u8 *addr)
971 {
972         struct nl_msg *msg, *flags = NULL;
973         int ifidx;
974         struct ifreq ifreq;
975         struct iwreq iwr;
976         int ret = -ENOBUFS;
977
978         msg = nlmsg_alloc();
979         if (!msg)
980                 return -1;
981
982         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
983                     0, NL80211_CMD_NEW_INTERFACE, 0);
984         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
985         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
986         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
987
988         if (iftype == NL80211_IFTYPE_MONITOR) {
989                 int err;
990
991                 flags = nlmsg_alloc();
992                 if (!flags)
993                         goto nla_put_failure;
994
995                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
996
997                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
998
999                 nlmsg_free(flags);
1000
1001                 if (err)
1002                         goto nla_put_failure;
1003         }
1004
1005         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1006         if (ret) {
1007  nla_put_failure:
1008                 printf("Failed to create interface %s.\n", ifname);
1009                 return ret;
1010         }
1011
1012         ifidx = if_nametoindex(ifname);
1013
1014         if (ifidx <= 0)
1015                 return -1;
1016
1017         /* start listening for EAPOL on this interface */
1018         add_ifidx(drv, ifidx);
1019
1020         if (addr) {
1021                 switch (iftype) {
1022                 case NL80211_IFTYPE_AP:
1023                         os_strlcpy(ifreq.ifr_name, ifname, IFNAMSIZ);
1024                         memcpy(ifreq.ifr_hwaddr.sa_data, addr, ETH_ALEN);
1025                         ifreq.ifr_hwaddr.sa_family = ARPHRD_ETHER;
1026
1027                         if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifreq)) {
1028                                 nl80211_remove_iface(drv, ifidx);
1029                                 return -1;
1030                         }
1031                         break;
1032                 case NL80211_IFTYPE_WDS:
1033                         memset(&iwr, 0, sizeof(iwr));
1034                         os_strlcpy(iwr.ifr_name, ifname, IFNAMSIZ);
1035                         iwr.u.addr.sa_family = ARPHRD_ETHER;
1036                         memcpy(iwr.u.addr.sa_data, addr, ETH_ALEN);
1037                         if (ioctl(drv->ioctl_sock, SIOCSIWAP, &iwr))
1038                                 return -1;
1039                         break;
1040                 default:
1041                         /* nothing */
1042                         break;
1043                 }
1044         }
1045
1046         return ifidx;
1047 }
1048
1049
1050 static int i802_bss_add(void *priv, const char *ifname, const u8 *bssid)
1051 {
1052         struct i802_driver_data *drv = priv;
1053         int ifidx;
1054         struct i802_bss *bss;
1055
1056         bss = os_zalloc(sizeof(*bss));
1057         if (bss == NULL)
1058                 return -1;
1059         os_strlcpy(bss->iface, ifname, IFNAMSIZ);
1060
1061         ifidx = nl80211_create_iface(priv, ifname, NL80211_IFTYPE_AP, bssid);
1062         if (ifidx < 0) {
1063                 os_free(bss);
1064                 return -1;
1065         }
1066         if (hostapd_set_iface_flags(priv, ifname, 1)) {
1067                 nl80211_remove_iface(priv, ifidx);
1068                 os_free(bss);
1069                 return -1;
1070         }
1071         bss->next = drv->bss.next;
1072         drv->bss.next = bss;
1073         return 0;
1074 }
1075
1076
1077 static int i802_bss_remove(void *priv, const char *ifname)
1078 {
1079         struct i802_driver_data *drv = priv;
1080         struct i802_bss *bss, *prev;
1081         nl80211_remove_iface(priv, if_nametoindex(ifname));
1082         prev = &drv->bss;
1083         bss = drv->bss.next;
1084         while (bss) {
1085                 if (os_strncmp(ifname, bss->iface, IFNAMSIZ) == 0) {
1086                         prev->next = bss->next;
1087                         os_free(bss);
1088                         break;
1089                 }
1090                 prev = bss;
1091                 bss = bss->next;
1092         }
1093         return 0;
1094 }
1095
1096
1097 static int i802_set_beacon(const char *iface, void *priv,
1098                            const u8 *head, size_t head_len,
1099                            const u8 *tail, size_t tail_len, int dtim_period)
1100 {
1101         struct i802_driver_data *drv = priv;
1102         struct nl_msg *msg;
1103         u8 cmd = NL80211_CMD_NEW_BEACON;
1104         int ret;
1105         struct i802_bss *bss;
1106
1107         bss = get_bss(drv, iface);
1108         if (bss == NULL)
1109                 return -ENOENT;
1110
1111         msg = nlmsg_alloc();
1112         if (!msg)
1113                 return -ENOMEM;
1114
1115         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (iface=%s beacon_set=%d)",
1116                    iface, bss->beacon_set);
1117         if (bss->beacon_set)
1118                 cmd = NL80211_CMD_SET_BEACON;
1119
1120         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1121                     0, cmd, 0);
1122         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
1123         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
1124         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
1125         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, drv->beacon_int);
1126         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
1127
1128         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1129         if (!ret)
1130                 bss->beacon_set = 1;
1131         return ret;
1132  nla_put_failure:
1133         return -ENOBUFS;
1134 }
1135
1136
1137 static int i802_del_beacon(struct i802_driver_data *drv)
1138 {
1139         struct nl_msg *msg;
1140
1141         msg = nlmsg_alloc();
1142         if (!msg)
1143                 return -ENOMEM;
1144
1145         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1146                     0, NL80211_CMD_DEL_BEACON, 0);
1147         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1148
1149         return send_and_recv_msgs(drv, msg, NULL, NULL);
1150  nla_put_failure:
1151         return -ENOBUFS;
1152 }
1153
1154
1155 static int i802_set_privacy(const char *ifname, void *priv, int enabled)
1156 {
1157         struct i802_driver_data *drv = priv;
1158         struct iwreq iwr;
1159
1160         memset(&iwr, 0, sizeof(iwr));
1161
1162         os_strlcpy(iwr.ifr_name, ifname, IFNAMSIZ);
1163         iwr.u.param.flags = IW_AUTH_PRIVACY_INVOKED;
1164         iwr.u.param.value = enabled;
1165
1166         ioctl(drv->ioctl_sock, SIOCSIWAUTH, &iwr);
1167
1168         /* ignore errors, the kernel/driver might not care */
1169         return 0;
1170 }
1171
1172
1173 static int i802_set_internal_bridge(void *priv, int value)
1174 {
1175         return -1;
1176 }
1177
1178
1179 static int i802_set_beacon_int(void *priv, int value)
1180 {
1181         struct i802_driver_data *drv = priv;
1182         struct nl_msg *msg;
1183
1184         drv->beacon_int = value;
1185
1186         if (!drv->bss.beacon_set)
1187                 return 0;
1188
1189         msg = nlmsg_alloc();
1190         if (!msg)
1191                 return -ENOMEM;
1192
1193         wpa_printf(MSG_DEBUG, "nl80211: Set beacon interval %d "
1194                    "(beacon_set=%d)", value, drv->bss.beacon_set);
1195         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1196                     0, NL80211_CMD_SET_BEACON, 0);
1197         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1198
1199         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, value);
1200
1201         return send_and_recv_msgs(drv, msg, NULL, NULL);
1202  nla_put_failure:
1203         return -ENOBUFS;
1204 }
1205
1206
1207 static int i802_set_bss(void *priv, int cts, int preamble, int slot)
1208 {
1209         struct i802_driver_data *drv = priv;
1210         struct nl_msg *msg;
1211
1212         msg = nlmsg_alloc();
1213         if (!msg)
1214                 return -ENOMEM;
1215
1216         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1217                     NL80211_CMD_SET_BSS, 0);
1218
1219         if (cts >= 0)
1220                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
1221         if (preamble >= 0)
1222                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
1223         if (slot >= 0)
1224                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
1225
1226         /* TODO: multi-BSS support */
1227         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1228
1229         return send_and_recv_msgs(drv, msg, NULL, NULL);
1230  nla_put_failure:
1231         return -ENOBUFS;
1232 }
1233
1234
1235 static int i802_set_cts_protect(void *priv, int value)
1236 {
1237         return i802_set_bss(priv, value, -1, -1);
1238 }
1239
1240
1241 static int i802_set_preamble(void *priv, int value)
1242 {
1243         return i802_set_bss(priv, -1, value, -1);
1244 }
1245
1246
1247 static int i802_set_short_slot_time(void *priv, int value)
1248 {
1249         return i802_set_bss(priv, -1, -1, value);
1250 }
1251
1252
1253 static enum nl80211_iftype i802_if_type(enum hostapd_driver_if_type type)
1254 {
1255         switch (type) {
1256         case HOSTAPD_IF_VLAN:
1257                 return NL80211_IFTYPE_AP_VLAN;
1258         case HOSTAPD_IF_WDS:
1259                 return NL80211_IFTYPE_WDS;
1260         }
1261         return -1;
1262 }
1263
1264
1265 static int i802_if_add(const char *iface, void *priv,
1266                        enum hostapd_driver_if_type type, char *ifname,
1267                        const u8 *addr)
1268 {
1269         if (nl80211_create_iface(priv, ifname, i802_if_type(type), addr) < 0)
1270                 return -1;
1271         return 0;
1272 }
1273
1274
1275 static int i802_if_update(void *priv, enum hostapd_driver_if_type type,
1276                           char *ifname, const u8 *addr)
1277 {
1278         /* unused at the moment */
1279         return -1;
1280 }
1281
1282
1283 static int i802_if_remove(void *priv, enum hostapd_driver_if_type type,
1284                           const char *ifname, const u8 *addr)
1285 {
1286         nl80211_remove_iface(priv, if_nametoindex(ifname));
1287         return 0;
1288 }
1289
1290
1291 struct phy_info_arg {
1292         u16 *num_modes;
1293         struct hostapd_hw_modes *modes;
1294 };
1295
1296 static int phy_info_handler(struct nl_msg *msg, void *arg)
1297 {
1298         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
1299         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1300         struct phy_info_arg *phy_info = arg;
1301
1302         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
1303
1304         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
1305         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
1306                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
1307                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
1308                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
1309                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
1310                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
1311                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
1312         };
1313
1314         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
1315         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
1316                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
1317                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
1318         };
1319
1320         struct nlattr *nl_band;
1321         struct nlattr *nl_freq;
1322         struct nlattr *nl_rate;
1323         int rem_band, rem_freq, rem_rate;
1324         struct hostapd_hw_modes *mode;
1325         int idx, mode_is_set;
1326
1327         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1328                   genlmsg_attrlen(gnlh, 0), NULL);
1329
1330         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
1331                 return NL_SKIP;
1332
1333         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
1334                 mode = realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
1335                 if (!mode)
1336                         return NL_SKIP;
1337                 phy_info->modes = mode;
1338
1339                 mode_is_set = 0;
1340
1341                 mode = &phy_info->modes[*(phy_info->num_modes)];
1342                 memset(mode, 0, sizeof(*mode));
1343                 *(phy_info->num_modes) += 1;
1344
1345                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
1346                           nla_len(nl_band), NULL);
1347
1348                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
1349                         mode->ht_capab = nla_get_u16(
1350                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
1351                 }
1352
1353                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
1354                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
1355                                   nla_len(nl_freq), freq_policy);
1356                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
1357                                 continue;
1358                         mode->num_channels++;
1359                 }
1360
1361                 mode->channels = calloc(mode->num_channels, sizeof(struct hostapd_channel_data));
1362                 if (!mode->channels)
1363                         return NL_SKIP;
1364
1365                 idx = 0;
1366
1367                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
1368                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
1369                                   nla_len(nl_freq), freq_policy);
1370                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
1371                                 continue;
1372
1373                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
1374                         mode->channels[idx].flag = 0;
1375
1376                         if (!mode_is_set) {
1377                                 /* crude heuristic */
1378                                 if (mode->channels[idx].freq < 4000)
1379                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
1380                                 else
1381                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
1382                                 mode_is_set = 1;
1383                         }
1384
1385                         /* crude heuristic */
1386                         if (mode->channels[idx].freq < 4000)
1387                                 if (mode->channels[idx].freq == 2848)
1388                                         mode->channels[idx].chan = 14;
1389                                 else
1390                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
1391                         else
1392                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
1393
1394                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
1395                                 mode->channels[idx].flag |=
1396                                         HOSTAPD_CHAN_DISABLED;
1397                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
1398                                 mode->channels[idx].flag |=
1399                                         HOSTAPD_CHAN_PASSIVE_SCAN;
1400                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
1401                                 mode->channels[idx].flag |=
1402                                         HOSTAPD_CHAN_NO_IBSS;
1403                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
1404                                 mode->channels[idx].flag |=
1405                                         HOSTAPD_CHAN_RADAR;
1406
1407                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
1408                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
1409                                 mode->channels[idx].max_tx_power =
1410                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
1411
1412                         idx++;
1413                 }
1414
1415                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
1416                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
1417                                   nla_len(nl_rate), rate_policy);
1418                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
1419                                 continue;
1420                         mode->num_rates++;
1421                 }
1422
1423                 mode->rates = calloc(mode->num_rates, sizeof(struct hostapd_rate_data));
1424                 if (!mode->rates)
1425                         return NL_SKIP;
1426
1427                 idx = 0;
1428
1429                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
1430                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
1431                                   nla_len(nl_rate), rate_policy);
1432                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
1433                                 continue;
1434                         mode->rates[idx].rate = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
1435
1436                         /* crude heuristic */
1437                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
1438                             mode->rates[idx].rate > 200)
1439                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
1440
1441                         if (tb_rate[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE])
1442                                 mode->rates[idx].flags |= HOSTAPD_RATE_PREAMBLE2;
1443
1444                         idx++;
1445                 }
1446         }
1447
1448         return NL_SKIP;
1449 }
1450
1451 static struct hostapd_hw_modes *i802_add_11b(struct hostapd_hw_modes *modes,
1452                                              u16 *num_modes)
1453 {
1454         u16 m;
1455         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
1456         int i, mode11g_idx = -1;
1457
1458         /* If only 802.11g mode is included, use it to construct matching
1459          * 802.11b mode data. */
1460
1461         for (m = 0; m < *num_modes; m++) {
1462                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
1463                         return modes; /* 802.11b already included */
1464                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
1465                         mode11g_idx = m;
1466         }
1467
1468         if (mode11g_idx < 0)
1469                 return modes; /* 2.4 GHz band not supported at all */
1470
1471         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
1472         if (nmodes == NULL)
1473                 return modes; /* Could not add 802.11b mode */
1474
1475         mode = &nmodes[*num_modes];
1476         os_memset(mode, 0, sizeof(*mode));
1477         (*num_modes)++;
1478         modes = nmodes;
1479
1480         mode->mode = HOSTAPD_MODE_IEEE80211B;
1481
1482         mode11g = &modes[mode11g_idx];
1483         mode->num_channels = mode11g->num_channels;
1484         mode->channels = os_malloc(mode11g->num_channels *
1485                                    sizeof(struct hostapd_channel_data));
1486         if (mode->channels == NULL) {
1487                 (*num_modes)--;
1488                 return modes; /* Could not add 802.11b mode */
1489         }
1490         os_memcpy(mode->channels, mode11g->channels,
1491                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
1492
1493         mode->num_rates = 0;
1494         mode->rates = os_malloc(4 * sizeof(struct hostapd_rate_data));
1495         if (mode->rates == NULL) {
1496                 os_free(mode->channels);
1497                 (*num_modes)--;
1498                 return modes; /* Could not add 802.11b mode */
1499         }
1500
1501         for (i = 0; i < mode11g->num_rates; i++) {
1502                 if (mode11g->rates[i].rate > 110 ||
1503                     mode11g->rates[i].flags &
1504                     (HOSTAPD_RATE_ERP | HOSTAPD_RATE_OFDM))
1505                         continue;
1506                 mode->rates[mode->num_rates] = mode11g->rates[i];
1507                 mode->num_rates++;
1508                 if (mode->num_rates == 4)
1509                         break;
1510         }
1511
1512         if (mode->num_rates == 0) {
1513                 os_free(mode->channels);
1514                 os_free(mode->rates);
1515                 (*num_modes)--;
1516                 return modes; /* No 802.11b rates */
1517         }
1518
1519         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
1520                    "information");
1521
1522         return modes;
1523 }
1524
1525 static struct hostapd_hw_modes *i802_get_hw_feature_data(void *priv,
1526                                                          u16 *num_modes,
1527                                                          u16 *flags)
1528 {
1529         struct i802_driver_data *drv = priv;
1530         struct nl_msg *msg;
1531         struct phy_info_arg result = {
1532                 .num_modes = num_modes,
1533                 .modes = NULL,
1534         };
1535
1536         *num_modes = 0;
1537         *flags = 0;
1538
1539         msg = nlmsg_alloc();
1540         if (!msg)
1541                 return NULL;
1542
1543         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1544                     0, NL80211_CMD_GET_WIPHY, 0);
1545
1546         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1547
1548         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0)
1549                 return i802_add_11b(result.modes, num_modes);
1550  nla_put_failure:
1551         return NULL;
1552 }
1553
1554
1555 static int i802_set_sta_vlan(void *priv, const u8 *addr,
1556                              const char *ifname, int vlan_id)
1557 {
1558         struct i802_driver_data *drv = priv;
1559         struct nl_msg *msg;
1560
1561         msg = nlmsg_alloc();
1562         if (!msg)
1563                 return -ENOMEM;
1564
1565         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1566                     0, NL80211_CMD_SET_STATION, 0);
1567
1568         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
1569                     if_nametoindex(drv->iface));
1570         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
1571         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
1572                     if_nametoindex(ifname));
1573
1574         return send_and_recv_msgs(drv, msg, NULL, NULL);
1575  nla_put_failure:
1576         return -ENOBUFS;
1577 }
1578
1579
1580 static int i802_set_country(void *priv, const char *country)
1581 {
1582         struct i802_driver_data *drv = priv;
1583         struct nl_msg *msg;
1584         char alpha2[3];
1585
1586         msg = nlmsg_alloc();
1587         if (!msg)
1588                 return -ENOMEM;
1589
1590         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1591                     0, NL80211_CMD_REQ_SET_REG, 0);
1592
1593         alpha2[0] = country[0];
1594         alpha2[1] = country[1];
1595         alpha2[2] = '\0';
1596         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
1597
1598         return send_and_recv_msgs(drv, msg, NULL, NULL);
1599  nla_put_failure:
1600         return -ENOBUFS;
1601 }
1602
1603
1604 static void handle_tx_callback(struct hostapd_data *hapd, u8 *buf, size_t len,
1605                                int ok)
1606 {
1607         struct ieee80211_hdr *hdr;
1608         u16 fc, type, stype;
1609
1610         hdr = (struct ieee80211_hdr *) buf;
1611         fc = le_to_host16(hdr->frame_control);
1612
1613         type = WLAN_FC_GET_TYPE(fc);
1614         stype = WLAN_FC_GET_STYPE(fc);
1615
1616         switch (type) {
1617         case WLAN_FC_TYPE_MGMT:
1618                 wpa_printf(MSG_DEBUG, "MGMT (TX callback) %s",
1619                            ok ? "ACK" : "fail");
1620                 hostapd_mgmt_tx_cb(hapd, buf, len, stype, ok);
1621                 break;
1622         case WLAN_FC_TYPE_CTRL:
1623                 wpa_printf(MSG_DEBUG, "CTRL (TX callback) %s",
1624                            ok ? "ACK" : "fail");
1625                 break;
1626         case WLAN_FC_TYPE_DATA:
1627                 hostapd_tx_status(hapd, hdr->addr1, buf, len, ok);
1628                 break;
1629         default:
1630                 printf("unknown TX callback frame type %d\n", type);
1631                 break;
1632         }
1633 }
1634
1635
1636 static void handle_frame(struct i802_driver_data *drv,
1637                          struct hostapd_iface *iface, u8 *buf, size_t len,
1638                          struct hostapd_frame_info *hfi,
1639                          enum ieee80211_msg_type msg_type)
1640 {
1641         struct ieee80211_hdr *hdr;
1642         u16 fc, type, stype;
1643         size_t data_len = len;
1644         struct hostapd_data *hapd = NULL;
1645         int broadcast_bssid = 0;
1646         size_t i;
1647         u8 *bssid;
1648
1649         /*
1650          * PS-Poll frames are 16 bytes. All other frames are
1651          * 24 bytes or longer.
1652          */
1653         if (len < 16)
1654                 return;
1655
1656         hdr = (struct ieee80211_hdr *) buf;
1657         fc = le_to_host16(hdr->frame_control);
1658
1659         type = WLAN_FC_GET_TYPE(fc);
1660         stype = WLAN_FC_GET_STYPE(fc);
1661
1662         switch (type) {
1663         case WLAN_FC_TYPE_DATA:
1664                 if (len < 24)
1665                         return;
1666                 switch (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) {
1667                 case WLAN_FC_TODS:
1668                         bssid = hdr->addr1;
1669                         break;
1670                 case WLAN_FC_FROMDS:
1671                         bssid = hdr->addr2;
1672                         break;
1673                 default:
1674                         /* discard */
1675                         return;
1676                 }
1677                 break;
1678         case WLAN_FC_TYPE_CTRL:
1679                 /* discard non-ps-poll frames */
1680                 if (stype != WLAN_FC_STYPE_PSPOLL)
1681                         return;
1682                 bssid = hdr->addr1;
1683                 break;
1684         case WLAN_FC_TYPE_MGMT:
1685                 bssid = hdr->addr3;
1686                 break;
1687         default:
1688                 /* discard */
1689                 return;
1690         }
1691
1692         /* find interface frame belongs to */
1693         for (i = 0; i < iface->num_bss; i++) {
1694                 if (memcmp(bssid, iface->bss[i]->own_addr, ETH_ALEN) == 0) {
1695                         hapd = iface->bss[i];
1696                         break;
1697                 }
1698         }
1699
1700         if (hapd == NULL) {
1701                 hapd = iface->bss[0];
1702
1703                 if (bssid[0] != 0xff || bssid[1] != 0xff ||
1704                     bssid[2] != 0xff || bssid[3] != 0xff ||
1705                     bssid[4] != 0xff || bssid[5] != 0xff) {
1706                         /*
1707                          * Unknown BSSID - drop frame if this is not from
1708                          * passive scanning or a beacon (at least ProbeReq
1709                          * frames to other APs may be allowed through RX
1710                          * filtering in the wlan hw/driver)
1711                          */
1712                         if ((type != WLAN_FC_TYPE_MGMT ||
1713                              stype != WLAN_FC_STYPE_BEACON))
1714                                 return;
1715                 } else
1716                         broadcast_bssid = 1;
1717         }
1718
1719         switch (msg_type) {
1720         case ieee80211_msg_normal:
1721                 /* continue processing */
1722                 break;
1723         case ieee80211_msg_tx_callback_ack:
1724                 handle_tx_callback(hapd, buf, data_len, 1);
1725                 return;
1726         case ieee80211_msg_tx_callback_fail:
1727                 handle_tx_callback(hapd, buf, data_len, 0);
1728                 return;
1729         }
1730
1731         switch (type) {
1732         case WLAN_FC_TYPE_MGMT:
1733                 if (stype != WLAN_FC_STYPE_BEACON &&
1734                     stype != WLAN_FC_STYPE_PROBE_REQ)
1735                         wpa_printf(MSG_MSGDUMP, "MGMT");
1736                 if (broadcast_bssid) {
1737                         for (i = 0; i < iface->num_bss; i++)
1738                                 hostapd_mgmt_rx(iface->bss[i], buf, data_len,
1739                                                 stype, hfi);
1740                 } else
1741                         hostapd_mgmt_rx(hapd, buf, data_len, stype, hfi);
1742                 break;
1743         case WLAN_FC_TYPE_CTRL:
1744                 /* can only get here with PS-Poll frames */
1745                 wpa_printf(MSG_DEBUG, "CTRL");
1746                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
1747                 break;
1748         case WLAN_FC_TYPE_DATA:
1749                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
1750                 break;
1751         }
1752 }
1753
1754
1755 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
1756 {
1757         struct i802_driver_data *drv = eloop_ctx;
1758         struct hostapd_data *hapd = drv->hapd;
1759         struct sockaddr_ll lladdr;
1760         unsigned char buf[3000];
1761         int len;
1762         socklen_t fromlen = sizeof(lladdr);
1763
1764         len = recvfrom(sock, buf, sizeof(buf), 0,
1765                        (struct sockaddr *)&lladdr, &fromlen);
1766         if (len < 0) {
1767                 perror("recv");
1768                 return;
1769         }
1770
1771         if (have_ifidx(drv, lladdr.sll_ifindex))
1772                 hostapd_eapol_receive(hapd, lladdr.sll_addr, buf, len);
1773 }
1774
1775
1776 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
1777 {
1778         struct i802_driver_data *drv = eloop_ctx;
1779         int len;
1780         unsigned char buf[3000];
1781         struct hostapd_data *hapd = drv->hapd;
1782         struct ieee80211_radiotap_iterator iter;
1783         int ret;
1784         struct hostapd_frame_info hfi;
1785         int injected = 0, failed = 0, msg_type, rxflags = 0;
1786
1787         len = recv(sock, buf, sizeof(buf), 0);
1788         if (len < 0) {
1789                 perror("recv");
1790                 return;
1791         }
1792
1793         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
1794                 printf("received invalid radiotap frame\n");
1795                 return;
1796         }
1797
1798         memset(&hfi, 0, sizeof(hfi));
1799
1800         while (1) {
1801                 ret = ieee80211_radiotap_iterator_next(&iter);
1802                 if (ret == -ENOENT)
1803                         break;
1804                 if (ret) {
1805                         printf("received invalid radiotap frame (%d)\n", ret);
1806                         return;
1807                 }
1808                 switch (iter.this_arg_index) {
1809                 case IEEE80211_RADIOTAP_FLAGS:
1810                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
1811                                 len -= 4;
1812                         break;
1813                 case IEEE80211_RADIOTAP_RX_FLAGS:
1814                         rxflags = 1;
1815                         break;
1816                 case IEEE80211_RADIOTAP_TX_FLAGS:
1817                         injected = 1;
1818                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
1819                                         IEEE80211_RADIOTAP_F_TX_FAIL;
1820                         break;
1821                 case IEEE80211_RADIOTAP_DATA_RETRIES:
1822                         break;
1823                 case IEEE80211_RADIOTAP_CHANNEL:
1824                         /* TODO convert from freq/flags to channel number
1825                         hfi.channel = XXX;
1826                         hfi.phytype = XXX;
1827                          */
1828                         break;
1829                 case IEEE80211_RADIOTAP_RATE:
1830                         hfi.datarate = *iter.this_arg * 5;
1831                         break;
1832                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
1833                         hfi.ssi_signal = *iter.this_arg;
1834                         break;
1835                 }
1836         }
1837
1838         if (rxflags && injected)
1839                 return;
1840
1841         if (!injected)
1842                 msg_type = ieee80211_msg_normal;
1843         else if (failed)
1844                 msg_type = ieee80211_msg_tx_callback_fail;
1845         else
1846                 msg_type = ieee80211_msg_tx_callback_ack;
1847
1848         handle_frame(drv, hapd->iface, buf + iter.max_length,
1849                      len - iter.max_length, &hfi, msg_type);
1850 }
1851
1852
1853 /*
1854  * we post-process the filter code later and rewrite
1855  * this to the offset to the last instruction
1856  */
1857 #define PASS    0xFF
1858 #define FAIL    0xFE
1859
1860 static struct sock_filter msock_filter_insns[] = {
1861         /*
1862          * do a little-endian load of the radiotap length field
1863          */
1864         /* load lower byte into A */
1865         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
1866         /* put it into X (== index register) */
1867         BPF_STMT(BPF_MISC| BPF_TAX, 0),
1868         /* load upper byte into A */
1869         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
1870         /* left-shift it by 8 */
1871         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
1872         /* or with X */
1873         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
1874         /* put result into X */
1875         BPF_STMT(BPF_MISC| BPF_TAX, 0),
1876
1877         /*
1878          * Allow management frames through, this also gives us those
1879          * management frames that we sent ourselves with status
1880          */
1881         /* load the lower byte of the IEEE 802.11 frame control field */
1882         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
1883         /* mask off frame type and version */
1884         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
1885         /* accept frame if it's both 0, fall through otherwise */
1886         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
1887
1888         /*
1889          * TODO: add a bit to radiotap RX flags that indicates
1890          * that the sending station is not associated, then
1891          * add a filter here that filters on our DA and that flag
1892          * to allow us to deauth frames to that bad station.
1893          *
1894          * Not a regression -- we didn't do it before either.
1895          */
1896
1897 #if 0
1898         /*
1899          * drop non-data frames, WDS frames
1900          */
1901         /* load the lower byte of the frame control field */
1902         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
1903         /* mask off QoS bit */
1904         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
1905         /* drop non-data frames */
1906         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
1907         /* load the upper byte of the frame control field */
1908         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
1909         /* mask off toDS/fromDS */
1910         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
1911         /* drop WDS frames */
1912         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, FAIL, 0),
1913 #endif
1914
1915         /*
1916          * add header length to index
1917          */
1918         /* load the lower byte of the frame control field */
1919         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
1920         /* mask off QoS bit */
1921         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
1922         /* right shift it by 6 to give 0 or 2 */
1923         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
1924         /* add data frame header length */
1925         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
1926         /* add index, was start of 802.11 header */
1927         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
1928         /* move to index, now start of LL header */
1929         BPF_STMT(BPF_MISC | BPF_TAX, 0),
1930
1931         /*
1932          * Accept empty data frames, we use those for
1933          * polling activity.
1934          */
1935         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
1936         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
1937
1938         /*
1939          * Accept EAPOL frames
1940          */
1941         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
1942         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
1943         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
1944         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
1945
1946         /* keep these last two statements or change the code below */
1947         /* return 0 == "DROP" */
1948         BPF_STMT(BPF_RET | BPF_K, 0),
1949         /* return ~0 == "keep all" */
1950         BPF_STMT(BPF_RET | BPF_K, ~0),
1951 };
1952
1953 static struct sock_fprog msock_filter = {
1954         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
1955         .filter = msock_filter_insns,
1956 };
1957
1958
1959 static int add_monitor_filter(int s)
1960 {
1961         int idx;
1962
1963         /* rewrite all PASS/FAIL jump offsets */
1964         for (idx = 0; idx < msock_filter.len; idx++) {
1965                 struct sock_filter *insn = &msock_filter_insns[idx];
1966
1967                 if (BPF_CLASS(insn->code) == BPF_JMP) {
1968                         if (insn->code == (BPF_JMP|BPF_JA)) {
1969                                 if (insn->k == PASS)
1970                                         insn->k = msock_filter.len - idx - 2;
1971                                 else if (insn->k == FAIL)
1972                                         insn->k = msock_filter.len - idx - 3;
1973                         }
1974
1975                         if (insn->jt == PASS)
1976                                 insn->jt = msock_filter.len - idx - 2;
1977                         else if (insn->jt == FAIL)
1978                                 insn->jt = msock_filter.len - idx - 3;
1979
1980                         if (insn->jf == PASS)
1981                                 insn->jf = msock_filter.len - idx - 2;
1982                         else if (insn->jf == FAIL)
1983                                 insn->jf = msock_filter.len - idx - 3;
1984                 }
1985         }
1986
1987         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
1988                        &msock_filter, sizeof(msock_filter))) {
1989                 perror("SO_ATTACH_FILTER");
1990                 return -1;
1991         }
1992
1993         return 0;
1994 }
1995
1996
1997 static int nl80211_create_monitor_interface(struct i802_driver_data *drv)
1998 {
1999         char buf[IFNAMSIZ];
2000         struct sockaddr_ll ll;
2001         int optval;
2002         socklen_t optlen;
2003
2004         snprintf(buf, IFNAMSIZ, "mon.%s", drv->iface);
2005         buf[IFNAMSIZ - 1] = '\0';
2006
2007         drv->monitor_ifidx =
2008                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL);
2009
2010         if (drv->monitor_ifidx < 0)
2011                 return -1;
2012
2013         if (hostapd_set_iface_flags(drv, buf, 1))
2014                 goto error;
2015
2016         memset(&ll, 0, sizeof(ll));
2017         ll.sll_family = AF_PACKET;
2018         ll.sll_ifindex = drv->monitor_ifidx;
2019         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
2020         if (drv->monitor_sock < 0) {
2021                 perror("socket[PF_PACKET,SOCK_RAW]");
2022                 goto error;
2023         }
2024
2025         if (add_monitor_filter(drv->monitor_sock)) {
2026                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
2027                            "interface; do filtering in user space");
2028                 /* This works, but will cost in performance. */
2029         }
2030
2031         if (bind(drv->monitor_sock, (struct sockaddr *) &ll,
2032                  sizeof(ll)) < 0) {
2033                 perror("monitor socket bind");
2034                 goto error;
2035         }
2036
2037         optlen = sizeof(optval);
2038         optval = 20;
2039         if (setsockopt
2040             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
2041                 perror("Failed to set socket priority");
2042                 goto error;
2043         }
2044
2045         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
2046                                      drv, NULL)) {
2047                 printf("Could not register monitor read socket\n");
2048                 goto error;
2049         }
2050
2051         return 0;
2052  error:
2053         nl80211_remove_iface(drv, drv->monitor_ifidx);
2054         return -1;
2055 }
2056
2057
2058 static int nl80211_set_mode(struct i802_driver_data *drv, const char *ifname,
2059                             int mode)
2060 {
2061         struct nl_msg *msg;
2062         int ret = -ENOBUFS;
2063
2064         msg = nlmsg_alloc();
2065         if (!msg)
2066                 return -ENOMEM;
2067
2068         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2069                     0, NL80211_CMD_SET_INTERFACE, 0);
2070         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
2071                     if_nametoindex(ifname));
2072         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
2073
2074         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2075         if (!ret)
2076                 return 0;
2077  nla_put_failure:
2078         wpa_printf(MSG_ERROR, "Failed to set interface %s to master "
2079                    "mode.", ifname);
2080         return ret;
2081 }
2082
2083
2084 #ifdef CONFIG_IEEE80211N
2085 static void i802_add_neighbor(struct i802_driver_data *drv, u8 *bssid,
2086                               int freq, u8 *ie, size_t ie_len)
2087 {
2088         struct ieee802_11_elems elems;
2089         int ht, pri_chan = 0, sec_chan = 0;
2090         struct ieee80211_ht_operation *oper;
2091         struct hostapd_neighbor_bss *nnei;
2092
2093         ieee802_11_parse_elems(ie, ie_len, &elems, 0);
2094         ht = elems.ht_capabilities || elems.ht_operation;
2095         if (elems.ht_operation && elems.ht_operation_len >= sizeof(*oper)) {
2096                 oper = (struct ieee80211_ht_operation *) elems.ht_operation;
2097                 pri_chan = oper->control_chan;
2098                 if (oper->ht_param & HT_INFO_HT_PARAM_REC_TRANS_CHNL_WIDTH) {
2099                         if (oper->ht_param &
2100                             HT_INFO_HT_PARAM_SECONDARY_CHNL_ABOVE)
2101                                 sec_chan = pri_chan + 4;
2102                         else if (oper->ht_param &
2103                             HT_INFO_HT_PARAM_SECONDARY_CHNL_BELOW)
2104                                 sec_chan = pri_chan - 4;
2105                 }
2106         }
2107
2108         wpa_printf(MSG_DEBUG, "nl80211: Neighboring BSS - bssid=" MACSTR
2109                    " freq=%d MHz HT=%d pri_chan=%d sec_chan=%d",
2110                    MAC2STR(bssid), freq, ht, pri_chan, sec_chan);
2111
2112         nnei = os_realloc(drv->neighbors, (drv->num_neighbors + 1) *
2113                           sizeof(struct hostapd_neighbor_bss));
2114         if (nnei == NULL)
2115                 return;
2116         drv->neighbors = nnei;
2117         nnei = &nnei[drv->num_neighbors];
2118         os_memcpy(nnei->bssid, bssid, ETH_ALEN);
2119         nnei->freq = freq;
2120         nnei->ht = !!ht;
2121         nnei->pri_chan = pri_chan;
2122         nnei->sec_chan = sec_chan;
2123         drv->num_neighbors++;
2124 }
2125
2126
2127 static int i802_get_scan_freq(struct iw_event *iwe, int *freq)
2128 {
2129         int divi = 1000000, i;
2130
2131         if (iwe->u.freq.e == 0) {
2132                 /*
2133                  * Some drivers do not report frequency, but a channel.
2134                  * Try to map this to frequency by assuming they are using
2135                  * IEEE 802.11b/g.  But don't overwrite a previously parsed
2136                  * frequency if the driver sends both frequency and channel,
2137                  * since the driver may be sending an A-band channel that we
2138                  * don't handle here.
2139                  */
2140
2141                 if (*freq)
2142                         return 0;
2143
2144                 if (iwe->u.freq.m >= 1 && iwe->u.freq.m <= 13) {
2145                         *freq = 2407 + 5 * iwe->u.freq.m;
2146                         return 0;
2147                 } else if (iwe->u.freq.m == 14) {
2148                         *freq = 2484;
2149                         return 0;
2150                 }
2151         }
2152
2153         if (iwe->u.freq.e > 6) {
2154                 wpa_printf(MSG_DEBUG, "Invalid freq in scan results: "
2155                            "m=%d e=%d", iwe->u.freq.m, iwe->u.freq.e);
2156                 return -1;
2157         }
2158
2159         for (i = 0; i < iwe->u.freq.e; i++)
2160                 divi /= 10;
2161         *freq = iwe->u.freq.m / divi;
2162         return 0;
2163 }
2164
2165
2166 static int i802_parse_scan(struct i802_driver_data *drv, u8 *res_buf,
2167                            size_t len)
2168 {
2169         size_t ap_num = 0;
2170         int first;
2171         struct iw_event iwe_buf, *iwe = &iwe_buf;
2172         char *pos, *end, *custom;
2173         u8 bssid[ETH_ALEN];
2174         int freq = 0;
2175         u8 *ie = NULL;
2176         size_t ie_len = 0;
2177
2178         ap_num = 0;
2179         first = 1;
2180
2181         pos = (char *) res_buf;
2182         end = (char *) res_buf + len;
2183
2184         while (pos + IW_EV_LCP_LEN <= end) {
2185                 /* Event data may be unaligned, so make a local, aligned copy
2186                  * before processing. */
2187                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
2188                 if (iwe->len <= IW_EV_LCP_LEN)
2189                         break;
2190
2191                 custom = pos + IW_EV_POINT_LEN;
2192                 if (iwe->cmd == IWEVGENIE) {
2193                         /* WE-19 removed the pointer from struct iw_point */
2194                         char *dpos = (char *) &iwe_buf.u.data.length;
2195                         int dlen = dpos - (char *) &iwe_buf;
2196                         os_memcpy(dpos, pos + IW_EV_LCP_LEN,
2197                                   sizeof(struct iw_event) - dlen);
2198                 } else {
2199                         os_memcpy(&iwe_buf, pos, sizeof(struct iw_event));
2200                         custom += IW_EV_POINT_OFF;
2201                 }
2202
2203                 switch (iwe->cmd) {
2204                 case SIOCGIWAP:
2205                         if (!first)
2206                                 i802_add_neighbor(drv, bssid, freq, ie,
2207                                                   ie_len);
2208                         first = 0;
2209                         os_memcpy(bssid, iwe->u.ap_addr.sa_data, ETH_ALEN);
2210                         freq = 0;
2211                         ie = NULL;
2212                         ie_len = 0;
2213                         break;
2214                 case SIOCGIWFREQ:
2215                         i802_get_scan_freq(iwe, &freq);
2216                         break;
2217                 case IWEVGENIE:
2218                         if (custom + iwe->u.data.length > end) {
2219                                 wpa_printf(MSG_ERROR, "IWEVGENIE overflow");
2220                                 return -1;
2221                         }
2222                         ie = (u8 *) custom;
2223                         ie_len = iwe->u.data.length;
2224                         break;
2225                 }
2226
2227                 pos += iwe->len;
2228         }
2229
2230         if (!first)
2231                 i802_add_neighbor(drv, bssid, freq, ie, ie_len);
2232
2233         return 0;
2234 }
2235
2236
2237 static int i802_get_ht_scan_res(struct i802_driver_data *drv)
2238 {
2239         struct iwreq iwr;
2240         u8 *res_buf;
2241         size_t res_buf_len;
2242         int res;
2243
2244         res_buf_len = IW_SCAN_MAX_DATA;
2245         for (;;) {
2246                 res_buf = os_malloc(res_buf_len);
2247                 if (res_buf == NULL)
2248                         return -1;
2249                 os_memset(&iwr, 0, sizeof(iwr));
2250                 os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
2251                 iwr.u.data.pointer = res_buf;
2252                 iwr.u.data.length = res_buf_len;
2253
2254                 if (ioctl(drv->ioctl_sock, SIOCGIWSCAN, &iwr) == 0)
2255                         break;
2256
2257                 if (errno == E2BIG && res_buf_len < 65535) {
2258                         os_free(res_buf);
2259                         res_buf = NULL;
2260                         res_buf_len *= 2;
2261                         if (res_buf_len > 65535)
2262                                 res_buf_len = 65535; /* 16-bit length field */
2263                         wpa_printf(MSG_DEBUG, "Scan results did not fit - "
2264                                    "trying larger buffer (%lu bytes)",
2265                                    (unsigned long) res_buf_len);
2266                 } else {
2267                         perror("ioctl[SIOCGIWSCAN]");
2268                         os_free(res_buf);
2269                         return -1;
2270                 }
2271         }
2272
2273         if (iwr.u.data.length > res_buf_len) {
2274                 os_free(res_buf);
2275                 return -1;
2276         }
2277
2278         res = i802_parse_scan(drv, res_buf, iwr.u.data.length);
2279         os_free(res_buf);
2280
2281         return res;
2282 }
2283
2284
2285 static int i802_is_event_wireless_scan_complete(char *data, int len)
2286 {
2287         struct iw_event iwe_buf, *iwe = &iwe_buf;
2288         char *pos, *end;
2289
2290         pos = data;
2291         end = data + len;
2292
2293         while (pos + IW_EV_LCP_LEN <= end) {
2294                 /* Event data may be unaligned, so make a local, aligned copy
2295                  * before processing. */
2296                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
2297                 if (iwe->cmd == SIOCGIWSCAN)
2298                         return 1;
2299
2300                 pos += iwe->len;
2301         }
2302
2303         return 0;
2304 }
2305
2306
2307 static int i802_is_rtm_scan_complete(int ifindex, struct nlmsghdr *h, int len)
2308 {
2309         struct ifinfomsg *ifi;
2310         int attrlen, _nlmsg_len, rta_len;
2311         struct rtattr *attr;
2312
2313         if (len < (int) sizeof(*ifi))
2314                 return 0;
2315
2316         ifi = NLMSG_DATA(h);
2317
2318         if (ifindex != ifi->ifi_index)
2319                 return 0; /* event for foreign ifindex */
2320
2321         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
2322
2323         attrlen = h->nlmsg_len - _nlmsg_len;
2324         if (attrlen < 0)
2325                 return 0;
2326
2327         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
2328
2329         rta_len = RTA_ALIGN(sizeof(struct rtattr));
2330         while (RTA_OK(attr, attrlen)) {
2331                 if (attr->rta_type == IFLA_WIRELESS &&
2332                     i802_is_event_wireless_scan_complete(
2333                             ((char *) attr) + rta_len,
2334                             attr->rta_len - rta_len))
2335                         return 1;
2336                 attr = RTA_NEXT(attr, attrlen);
2337         }
2338
2339         return 0;
2340 }
2341
2342
2343 static int i802_is_scan_complete(int s, int ifindex)
2344 {
2345         char buf[1024];
2346         int left;
2347         struct nlmsghdr *h;
2348
2349         left = recv(s, buf, sizeof(buf), MSG_DONTWAIT);
2350         if (left < 0) {
2351                 perror("recv(netlink)");
2352                 return 0;
2353         }
2354
2355         h = (struct nlmsghdr *) buf;
2356         while (left >= (int) sizeof(*h)) {
2357                 int len, plen;
2358
2359                 len = h->nlmsg_len;
2360                 plen = len - sizeof(*h);
2361                 if (len > left || plen < 0) {
2362                         wpa_printf(MSG_DEBUG, "Malformed netlink message: "
2363                                    "len=%d left=%d plen=%d",
2364                                    len, left, plen);
2365                         break;
2366                 }
2367
2368                 switch (h->nlmsg_type) {
2369                 case RTM_NEWLINK:
2370                         if (i802_is_rtm_scan_complete(ifindex, h, plen))
2371                                 return 1;
2372                         break;
2373                 }
2374
2375                 len = NLMSG_ALIGN(len);
2376                 left -= len;
2377                 h = (struct nlmsghdr *) ((char *) h + len);
2378         }
2379
2380         return 0;
2381 }
2382
2383
2384 static int i802_ht_scan(struct i802_driver_data *drv)
2385 {
2386         struct iwreq iwr;
2387         int s, res, ifindex;
2388         struct sockaddr_nl local;
2389         time_t now, end;
2390         fd_set rfds;
2391         struct timeval tv;
2392
2393         wpa_printf(MSG_DEBUG, "nl80211: Scanning overlapping BSSes before "
2394                    "starting HT 20/40 MHz BSS");
2395
2396         /* Request a new scan */
2397         /* TODO: would be enough to scan the selected band */
2398         os_memset(&iwr, 0, sizeof(iwr));
2399         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
2400         if (ioctl(drv->ioctl_sock, SIOCSIWSCAN, &iwr) < 0) {
2401                 perror("ioctl[SIOCSIWSCAN]");
2402                 return -1;
2403         }
2404
2405         ifindex = if_nametoindex(drv->iface);
2406
2407         /* Wait for scan completion event or timeout */
2408         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2409         if (s < 0) {
2410                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
2411                 return -1;
2412         }
2413
2414         os_memset(&local, 0, sizeof(local));
2415         local.nl_family = AF_NETLINK;
2416         local.nl_groups = RTMGRP_LINK;
2417         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
2418                 perror("bind(netlink)");
2419                 close(s);
2420                 return -1;
2421         }
2422
2423         time(&end);
2424         end += 30; /* Wait at most 30 seconds for scan results */
2425         for (;;) {
2426                 time(&now);
2427                 tv.tv_sec = end > now ? end - now : 0;
2428                 tv.tv_usec = 0;
2429                 FD_ZERO(&rfds);
2430                 FD_SET(s, &rfds);
2431                 res = select(s + 1, &rfds, NULL, NULL, &tv);
2432                 if (res < 0) {
2433                         perror("select");
2434                         /* Assume results are ready after 10 seconds wait */
2435                         os_sleep(10, 0);
2436                         break;
2437                 } else if (res) {
2438                         if (i802_is_scan_complete(s, ifindex)) {
2439                                 wpa_printf(MSG_DEBUG, "nl80211: Scan "
2440                                            "completed");
2441                                 break;
2442                         }
2443                 } else {
2444                         wpa_printf(MSG_DEBUG, "nl80211: Scan timeout");
2445                         /* Assume results are ready to be read now */
2446                         break;
2447                 }
2448         }
2449
2450         close(s);
2451
2452         return i802_get_ht_scan_res(drv);
2453 }
2454 #endif /* CONFIG_IEEE80211N */
2455
2456
2457 static int i802_init_sockets(struct i802_driver_data *drv, const u8 *bssid)
2458 {
2459         struct ifreq ifr;
2460         struct sockaddr_ll addr;
2461
2462         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
2463         if (drv->ioctl_sock < 0) {
2464                 perror("socket[PF_INET,SOCK_DGRAM]");
2465                 return -1;
2466         }
2467
2468         /* start listening for EAPOL on the default AP interface */
2469         add_ifidx(drv, if_nametoindex(drv->iface));
2470
2471         if (hostapd_set_iface_flags(drv, drv->iface, 0))
2472                 return -1;
2473
2474         if (bssid) {
2475                 os_strlcpy(ifr.ifr_name, drv->iface, IFNAMSIZ);
2476                 memcpy(ifr.ifr_hwaddr.sa_data, bssid, ETH_ALEN);
2477                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
2478
2479                 if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifr)) {
2480                         perror("ioctl(SIOCSIFHWADDR)");
2481                         return -1;
2482                 }
2483         }
2484
2485         /*
2486          * initialise generic netlink and nl80211
2487          */
2488         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2489         if (!drv->nl_cb) {
2490                 printf("Failed to allocate netlink callbacks.\n");
2491                 return -1;
2492         }
2493
2494         drv->nl_handle = nl_handle_alloc_cb(drv->nl_cb);
2495         if (!drv->nl_handle) {
2496                 printf("Failed to allocate netlink handle.\n");
2497                 return -1;
2498         }
2499
2500         if (genl_connect(drv->nl_handle)) {
2501                 printf("Failed to connect to generic netlink.\n");
2502                 return -1;
2503         }
2504
2505 #ifdef CONFIG_LIBNL20
2506         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
2507                 printf("Failed to allocate generic netlink cache.\n");
2508                 return -1;
2509         }
2510 #else /* CONFIG_LIBNL20 */
2511         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
2512         if (!drv->nl_cache) {
2513                 printf("Failed to allocate generic netlink cache.\n");
2514                 return -1;
2515         }
2516 #endif /* CONFIG_LIBNL20 */
2517
2518         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
2519         if (!drv->nl80211) {
2520                 printf("nl80211 not found.\n");
2521                 return -1;
2522         }
2523
2524 #ifdef CONFIG_IEEE80211N
2525         if (drv->ht_40mhz_scan) {
2526                 if (nl80211_set_mode(drv, drv->iface, NL80211_IFTYPE_STATION)
2527                     || hostapd_set_iface_flags(drv, drv->iface, 1) ||
2528                     i802_ht_scan(drv) ||
2529                     hostapd_set_iface_flags(drv, drv->iface, 0)) {
2530                         wpa_printf(MSG_ERROR, "Failed to scan channels for "
2531                                    "HT 40 MHz operations");
2532                         return -1;
2533                 }
2534         }
2535 #endif /* CONFIG_IEEE80211N */
2536
2537         /* Initialise a monitor interface */
2538         if (nl80211_create_monitor_interface(drv))
2539                 return -1;
2540
2541         if (nl80211_set_mode(drv, drv->iface, NL80211_IFTYPE_AP))
2542                 goto fail1;
2543
2544         if (hostapd_set_iface_flags(drv, drv->iface, 1))
2545                 goto fail1;
2546
2547         memset(&addr, 0, sizeof(addr));
2548         addr.sll_family = AF_PACKET;
2549         addr.sll_ifindex = ifr.ifr_ifindex;
2550         wpa_printf(MSG_DEBUG, "Opening raw packet socket for ifindex %d",
2551                    addr.sll_ifindex);
2552
2553         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
2554         if (drv->eapol_sock < 0) {
2555                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
2556                 goto fail1;
2557         }
2558
2559         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
2560         {
2561                 printf("Could not register read socket for eapol\n");
2562                 return -1;
2563         }
2564
2565         memset(&ifr, 0, sizeof(ifr));
2566         os_strlcpy(ifr.ifr_name, drv->iface, sizeof(ifr.ifr_name));
2567         if (ioctl(drv->ioctl_sock, SIOCGIFHWADDR, &ifr) != 0) {
2568                 perror("ioctl(SIOCGIFHWADDR)");
2569                 goto fail1;
2570         }
2571
2572         if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
2573                 printf("Invalid HW-addr family 0x%04x\n",
2574                        ifr.ifr_hwaddr.sa_family);
2575                 goto fail1;
2576         }
2577         memcpy(drv->hapd->own_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
2578
2579         return 0;
2580
2581 fail1:
2582         nl80211_remove_iface(drv, drv->monitor_ifidx);
2583         return -1;
2584 }
2585
2586
2587 static int i802_get_inact_sec(void *priv, const u8 *addr)
2588 {
2589         struct hostap_sta_driver_data data;
2590         int ret;
2591
2592         data.inactive_msec = (unsigned long) -1;
2593         ret = i802_read_sta_data(priv, &data, addr);
2594         if (ret || data.inactive_msec == (unsigned long) -1)
2595                 return -1;
2596         return data.inactive_msec / 1000;
2597 }
2598
2599
2600 static int i802_sta_clear_stats(void *priv, const u8 *addr)
2601 {
2602 #if 0
2603         /* TODO */
2604 #endif
2605         return 0;
2606 }
2607
2608
2609 static void
2610 hostapd_wireless_event_wireless_custom(struct i802_driver_data *drv,
2611                                        char *custom)
2612 {
2613         wpa_printf(MSG_DEBUG, "Custom wireless event: '%s'", custom);
2614
2615         if (strncmp(custom, "MLME-MICHAELMICFAILURE.indication", 33) == 0) {
2616                 char *pos;
2617                 u8 addr[ETH_ALEN];
2618                 pos = strstr(custom, "addr=");
2619                 if (pos == NULL) {
2620                         wpa_printf(MSG_DEBUG,
2621                                    "MLME-MICHAELMICFAILURE.indication "
2622                                    "without sender address ignored");
2623                         return;
2624                 }
2625                 pos += 5;
2626                 if (hwaddr_aton(pos, addr) == 0) {
2627                         hostapd_michael_mic_failure(drv->hapd, addr);
2628                 } else {
2629                         wpa_printf(MSG_DEBUG,
2630                                    "MLME-MICHAELMICFAILURE.indication "
2631                                    "with invalid MAC address");
2632                 }
2633         }
2634 }
2635
2636
2637 static void hostapd_wireless_event_wireless(struct i802_driver_data *drv,
2638                                             char *data, int len)
2639 {
2640         struct iw_event iwe_buf, *iwe = &iwe_buf;
2641         char *pos, *end, *custom, *buf;
2642
2643         pos = data;
2644         end = data + len;
2645
2646         while (pos + IW_EV_LCP_LEN <= end) {
2647                 /* Event data may be unaligned, so make a local, aligned copy
2648                  * before processing. */
2649                 memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
2650                 wpa_printf(MSG_DEBUG, "Wireless event: cmd=0x%x len=%d",
2651                            iwe->cmd, iwe->len);
2652                 if (iwe->len <= IW_EV_LCP_LEN)
2653                         return;
2654
2655                 custom = pos + IW_EV_POINT_LEN;
2656                 if (drv->we_version > 18 &&
2657                     (iwe->cmd == IWEVMICHAELMICFAILURE ||
2658                      iwe->cmd == IWEVCUSTOM)) {
2659                         /* WE-19 removed the pointer from struct iw_point */
2660                         char *dpos = (char *) &iwe_buf.u.data.length;
2661                         int dlen = dpos - (char *) &iwe_buf;
2662                         memcpy(dpos, pos + IW_EV_LCP_LEN,
2663                                sizeof(struct iw_event) - dlen);
2664                 } else {
2665                         memcpy(&iwe_buf, pos, sizeof(struct iw_event));
2666                         custom += IW_EV_POINT_OFF;
2667                 }
2668
2669                 switch (iwe->cmd) {
2670                 case IWEVCUSTOM:
2671                         if (custom + iwe->u.data.length > end)
2672                                 return;
2673                         buf = malloc(iwe->u.data.length + 1);
2674                         if (buf == NULL)
2675                                 return;
2676                         memcpy(buf, custom, iwe->u.data.length);
2677                         buf[iwe->u.data.length] = '\0';
2678                         hostapd_wireless_event_wireless_custom(drv, buf);
2679                         free(buf);
2680                         break;
2681                 }
2682
2683                 pos += iwe->len;
2684         }
2685 }
2686
2687
2688 static void hostapd_wireless_event_rtm_newlink(struct i802_driver_data *drv,
2689                                                struct nlmsghdr *h, int len)
2690 {
2691         struct ifinfomsg *ifi;
2692         int attrlen, _nlmsg_len, rta_len;
2693         struct rtattr *attr;
2694
2695         if (len < (int) sizeof(*ifi))
2696                 return;
2697
2698         ifi = NLMSG_DATA(h);
2699
2700         /* TODO: use ifi->ifi_index to filter out wireless events from other
2701          * interfaces */
2702
2703         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
2704
2705         attrlen = h->nlmsg_len - _nlmsg_len;
2706         if (attrlen < 0)
2707                 return;
2708
2709         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
2710
2711         rta_len = RTA_ALIGN(sizeof(struct rtattr));
2712         while (RTA_OK(attr, attrlen)) {
2713                 if (attr->rta_type == IFLA_WIRELESS) {
2714                         hostapd_wireless_event_wireless(
2715                                 drv, ((char *) attr) + rta_len,
2716                                 attr->rta_len - rta_len);
2717                 }
2718                 attr = RTA_NEXT(attr, attrlen);
2719         }
2720 }
2721
2722
2723 static void hostapd_wireless_event_receive(int sock, void *eloop_ctx,
2724                                            void *sock_ctx)
2725 {
2726         char buf[256];
2727         int left;
2728         struct sockaddr_nl from;
2729         socklen_t fromlen;
2730         struct nlmsghdr *h;
2731         struct i802_driver_data *drv = eloop_ctx;
2732
2733         fromlen = sizeof(from);
2734         left = recvfrom(sock, buf, sizeof(buf), MSG_DONTWAIT,
2735                         (struct sockaddr *) &from, &fromlen);
2736         if (left < 0) {
2737                 if (errno != EINTR && errno != EAGAIN)
2738                         perror("recvfrom(netlink)");
2739                 return;
2740         }
2741
2742         h = (struct nlmsghdr *) buf;
2743         while (left >= (int) sizeof(*h)) {
2744                 int len, plen;
2745
2746                 len = h->nlmsg_len;
2747                 plen = len - sizeof(*h);
2748                 if (len > left || plen < 0) {
2749                         printf("Malformed netlink message: "
2750                                "len=%d left=%d plen=%d\n",
2751                                len, left, plen);
2752                         break;
2753                 }
2754
2755                 switch (h->nlmsg_type) {
2756                 case RTM_NEWLINK:
2757                         hostapd_wireless_event_rtm_newlink(drv, h, plen);
2758                         break;
2759                 }
2760
2761                 len = NLMSG_ALIGN(len);
2762                 left -= len;
2763                 h = (struct nlmsghdr *) ((char *) h + len);
2764         }
2765
2766         if (left > 0) {
2767                 printf("%d extra bytes in the end of netlink message\n", left);
2768         }
2769 }
2770
2771
2772 static int hostap_get_we_version(struct i802_driver_data *drv)
2773 {
2774         struct iw_range *range;
2775         struct iwreq iwr;
2776         int minlen;
2777         size_t buflen;
2778
2779         drv->we_version = 0;
2780
2781         /*
2782          * Use larger buffer than struct iw_range in order to allow the
2783          * structure to grow in the future.
2784          */
2785         buflen = sizeof(struct iw_range) + 500;
2786         range = os_zalloc(buflen);
2787         if (range == NULL)
2788                 return -1;
2789
2790         memset(&iwr, 0, sizeof(iwr));
2791         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
2792         iwr.u.data.pointer = (caddr_t) range;
2793         iwr.u.data.length = buflen;
2794
2795         minlen = ((char *) &range->enc_capa) - (char *) range +
2796                 sizeof(range->enc_capa);
2797
2798         if (ioctl(drv->ioctl_sock, SIOCGIWRANGE, &iwr) < 0) {
2799                 perror("ioctl[SIOCGIWRANGE]");
2800                 free(range);
2801                 return -1;
2802         } else if (iwr.u.data.length >= minlen &&
2803                    range->we_version_compiled >= 18) {
2804                 wpa_printf(MSG_DEBUG, "SIOCGIWRANGE: WE(compiled)=%d "
2805                            "WE(source)=%d enc_capa=0x%x",
2806                            range->we_version_compiled,
2807                            range->we_version_source,
2808                            range->enc_capa);
2809                 drv->we_version = range->we_version_compiled;
2810         }
2811
2812         free(range);
2813         return 0;
2814 }
2815
2816
2817 static int i802_wireless_event_init(struct i802_driver_data *drv)
2818 {
2819         int s;
2820         struct sockaddr_nl local;
2821
2822         hostap_get_we_version(drv);
2823
2824         drv->wext_sock = -1;
2825
2826         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2827         if (s < 0) {
2828                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
2829                 return -1;
2830         }
2831
2832         memset(&local, 0, sizeof(local));
2833         local.nl_family = AF_NETLINK;
2834         local.nl_groups = RTMGRP_LINK;
2835         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
2836                 perror("bind(netlink)");
2837                 close(s);
2838                 return -1;
2839         }
2840
2841         eloop_register_read_sock(s, hostapd_wireless_event_receive, drv,
2842                                  NULL);
2843         drv->wext_sock = s;
2844
2845         return 0;
2846 }
2847
2848
2849 static void i802_wireless_event_deinit(struct i802_driver_data *drv)
2850 {
2851         if (drv->wext_sock < 0)
2852                 return;
2853         eloop_unregister_read_sock(drv->wext_sock);
2854         close(drv->wext_sock);
2855 }
2856
2857
2858 static int i802_sta_deauth(void *priv, const u8 *addr, int reason)
2859 {
2860         struct i802_driver_data *drv = priv;
2861         struct ieee80211_mgmt mgmt;
2862
2863         memset(&mgmt, 0, sizeof(mgmt));
2864         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
2865                                           WLAN_FC_STYPE_DEAUTH);
2866         memcpy(mgmt.da, addr, ETH_ALEN);
2867         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
2868         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
2869         mgmt.u.deauth.reason_code = host_to_le16(reason);
2870         return i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
2871                                       sizeof(mgmt.u.deauth), 0);
2872 }
2873
2874
2875 static int i802_sta_disassoc(void *priv, const u8 *addr, int reason)
2876 {
2877         struct i802_driver_data *drv = priv;
2878         struct ieee80211_mgmt mgmt;
2879
2880         memset(&mgmt, 0, sizeof(mgmt));
2881         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
2882                                           WLAN_FC_STYPE_DISASSOC);
2883         memcpy(mgmt.da, addr, ETH_ALEN);
2884         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
2885         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
2886         mgmt.u.disassoc.reason_code = host_to_le16(reason);
2887         return  i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
2888                                        sizeof(mgmt.u.disassoc), 0);
2889 }
2890
2891
2892 static const struct hostapd_neighbor_bss *
2893 i802_get_neighbor_bss(void *priv, size_t *num)
2894 {
2895         struct i802_driver_data *drv = priv;
2896         *num = drv->num_neighbors;
2897         return drv->neighbors;
2898 }
2899
2900
2901 static void *i802_init_bssid(struct hostapd_data *hapd, const u8 *bssid)
2902 {
2903         struct i802_driver_data *drv;
2904
2905         drv = os_zalloc(sizeof(struct i802_driver_data));
2906         if (drv == NULL) {
2907                 printf("Could not allocate memory for i802 driver data\n");
2908                 return NULL;
2909         }
2910
2911         drv->hapd = hapd;
2912         memcpy(drv->iface, hapd->conf->iface, sizeof(drv->iface));
2913         memcpy(drv->bss.iface, hapd->conf->iface, sizeof(drv->iface));
2914
2915         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
2916         drv->if_indices = drv->default_if_indices;
2917         drv->bridge = if_nametoindex(hapd->conf->bridge);
2918         drv->ht_40mhz_scan = hapd->iconf->secondary_channel != 0;
2919
2920         if (i802_init_sockets(drv, bssid))
2921                 goto failed;
2922
2923         if (i802_wireless_event_init(drv))
2924                 goto failed;
2925
2926         return drv;
2927
2928 failed:
2929         free(drv);
2930         return NULL;
2931 }
2932
2933
2934 static void *i802_init(struct hostapd_data *hapd)
2935 {
2936         return i802_init_bssid(hapd, NULL);
2937 }
2938
2939
2940 static void i802_deinit(void *priv)
2941 {
2942         struct i802_driver_data *drv = priv;
2943         struct i802_bss *bss, *prev;
2944
2945         i802_wireless_event_deinit(drv);
2946
2947         if (drv->last_freq_ht) {
2948                 /* Clear HT flags from the driver */
2949                 struct hostapd_freq_params freq;
2950                 os_memset(&freq, 0, sizeof(freq));
2951                 freq.freq = drv->last_freq;
2952                 i802_set_freq(priv, &freq);
2953         }
2954
2955         i802_del_beacon(drv);
2956
2957         /* remove monitor interface */
2958         nl80211_remove_iface(drv, drv->monitor_ifidx);
2959
2960         (void) hostapd_set_iface_flags(drv, drv->iface, 0);
2961
2962         if (drv->monitor_sock >= 0) {
2963                 eloop_unregister_read_sock(drv->monitor_sock);
2964                 close(drv->monitor_sock);
2965         }
2966         if (drv->ioctl_sock >= 0)
2967                 close(drv->ioctl_sock);
2968         if (drv->eapol_sock >= 0) {
2969                 eloop_unregister_read_sock(drv->eapol_sock);
2970                 close(drv->eapol_sock);
2971         }
2972
2973         genl_family_put(drv->nl80211);
2974         nl_cache_free(drv->nl_cache);
2975         nl_handle_destroy(drv->nl_handle);
2976         nl_cb_put(drv->nl_cb);
2977
2978         if (drv->if_indices != drv->default_if_indices)
2979                 free(drv->if_indices);
2980
2981         os_free(drv->neighbors);
2982
2983         bss = drv->bss.next;
2984         while (bss) {
2985                 prev = bss;
2986                 bss = bss->next;
2987                 os_free(bss);
2988         }
2989
2990         free(drv);
2991 }
2992
2993
2994 const struct hapd_driver_ops wpa_driver_nl80211_ops = {
2995         .name = "nl80211",
2996         .init = i802_init,
2997         .init_bssid = i802_init_bssid,
2998         .deinit = i802_deinit,
2999         .set_privacy = i802_set_privacy,
3000         .set_key = i802_set_key,
3001         .get_seqnum = i802_get_seqnum,
3002         .flush = i802_flush,
3003         .read_sta_data = i802_read_sta_data,
3004         .send_eapol = i802_send_eapol,
3005         .sta_set_flags = i802_sta_set_flags,
3006         .sta_deauth = i802_sta_deauth,
3007         .sta_disassoc = i802_sta_disassoc,
3008         .sta_remove = i802_sta_remove,
3009         .send_mgmt_frame = i802_send_mgmt_frame,
3010         .sta_add = i802_sta_add,
3011         .get_inact_sec = i802_get_inact_sec,
3012         .sta_clear_stats = i802_sta_clear_stats,
3013         .set_freq = i802_set_freq,
3014         .set_rts = i802_set_rts,
3015         .set_frag = i802_set_frag,
3016         .set_retry = i802_set_retry,
3017         .set_rate_sets = i802_set_rate_sets,
3018         .set_beacon = i802_set_beacon,
3019         .set_internal_bridge = i802_set_internal_bridge,
3020         .set_beacon_int = i802_set_beacon_int,
3021         .set_cts_protect = i802_set_cts_protect,
3022         .set_preamble = i802_set_preamble,
3023         .set_short_slot_time = i802_set_short_slot_time,
3024         .set_tx_queue_params = i802_set_tx_queue_params,
3025         .bss_add = i802_bss_add,
3026         .bss_remove = i802_bss_remove,
3027         .if_add = i802_if_add,
3028         .if_update = i802_if_update,
3029         .if_remove = i802_if_remove,
3030         .get_hw_feature_data = i802_get_hw_feature_data,
3031         .set_sta_vlan = i802_set_sta_vlan,
3032         .set_country = i802_set_country,
3033         .get_neighbor_bss = i802_get_neighbor_bss,
3034 };