78b9a55ae84fc99bc0c08f480ea80883953f4146
[libeap.git] / 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_beacon_int(void *priv, int value)
1156 {
1157         struct i802_driver_data *drv = priv;
1158         struct nl_msg *msg;
1159
1160         drv->beacon_int = value;
1161
1162         if (!drv->bss.beacon_set)
1163                 return 0;
1164
1165         msg = nlmsg_alloc();
1166         if (!msg)
1167                 return -ENOMEM;
1168
1169         wpa_printf(MSG_DEBUG, "nl80211: Set beacon interval %d "
1170                    "(beacon_set=%d)", value, drv->bss.beacon_set);
1171         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1172                     0, NL80211_CMD_SET_BEACON, 0);
1173         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1174
1175         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, value);
1176
1177         return send_and_recv_msgs(drv, msg, NULL, NULL);
1178  nla_put_failure:
1179         return -ENOBUFS;
1180 }
1181
1182
1183 static int i802_set_bss(void *priv, int cts, int preamble, int slot)
1184 {
1185         struct i802_driver_data *drv = priv;
1186         struct nl_msg *msg;
1187
1188         msg = nlmsg_alloc();
1189         if (!msg)
1190                 return -ENOMEM;
1191
1192         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1193                     NL80211_CMD_SET_BSS, 0);
1194
1195         if (cts >= 0)
1196                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
1197         if (preamble >= 0)
1198                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
1199         if (slot >= 0)
1200                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
1201
1202         /* TODO: multi-BSS support */
1203         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1204
1205         return send_and_recv_msgs(drv, msg, NULL, NULL);
1206  nla_put_failure:
1207         return -ENOBUFS;
1208 }
1209
1210
1211 static int i802_set_cts_protect(void *priv, int value)
1212 {
1213         return i802_set_bss(priv, value, -1, -1);
1214 }
1215
1216
1217 static int i802_set_preamble(void *priv, int value)
1218 {
1219         return i802_set_bss(priv, -1, value, -1);
1220 }
1221
1222
1223 static int i802_set_short_slot_time(void *priv, int value)
1224 {
1225         return i802_set_bss(priv, -1, -1, value);
1226 }
1227
1228
1229 static enum nl80211_iftype i802_if_type(enum hostapd_driver_if_type type)
1230 {
1231         switch (type) {
1232         case HOSTAPD_IF_VLAN:
1233                 return NL80211_IFTYPE_AP_VLAN;
1234         case HOSTAPD_IF_WDS:
1235                 return NL80211_IFTYPE_WDS;
1236         }
1237         return -1;
1238 }
1239
1240
1241 static int i802_if_add(const char *iface, void *priv,
1242                        enum hostapd_driver_if_type type, char *ifname,
1243                        const u8 *addr)
1244 {
1245         if (nl80211_create_iface(priv, ifname, i802_if_type(type), addr) < 0)
1246                 return -1;
1247         return 0;
1248 }
1249
1250
1251 static int i802_if_update(void *priv, enum hostapd_driver_if_type type,
1252                           char *ifname, const u8 *addr)
1253 {
1254         /* unused at the moment */
1255         return -1;
1256 }
1257
1258
1259 static int i802_if_remove(void *priv, enum hostapd_driver_if_type type,
1260                           const char *ifname, const u8 *addr)
1261 {
1262         nl80211_remove_iface(priv, if_nametoindex(ifname));
1263         return 0;
1264 }
1265
1266
1267 struct phy_info_arg {
1268         u16 *num_modes;
1269         struct hostapd_hw_modes *modes;
1270 };
1271
1272 static int phy_info_handler(struct nl_msg *msg, void *arg)
1273 {
1274         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
1275         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1276         struct phy_info_arg *phy_info = arg;
1277
1278         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
1279
1280         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
1281         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
1282                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
1283                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
1284                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
1285                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
1286                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
1287                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
1288         };
1289
1290         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
1291         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
1292                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
1293                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
1294         };
1295
1296         struct nlattr *nl_band;
1297         struct nlattr *nl_freq;
1298         struct nlattr *nl_rate;
1299         int rem_band, rem_freq, rem_rate;
1300         struct hostapd_hw_modes *mode;
1301         int idx, mode_is_set;
1302
1303         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1304                   genlmsg_attrlen(gnlh, 0), NULL);
1305
1306         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
1307                 return NL_SKIP;
1308
1309         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
1310                 mode = realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
1311                 if (!mode)
1312                         return NL_SKIP;
1313                 phy_info->modes = mode;
1314
1315                 mode_is_set = 0;
1316
1317                 mode = &phy_info->modes[*(phy_info->num_modes)];
1318                 memset(mode, 0, sizeof(*mode));
1319                 *(phy_info->num_modes) += 1;
1320
1321                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
1322                           nla_len(nl_band), NULL);
1323
1324                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
1325                         mode->ht_capab = nla_get_u16(
1326                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
1327                 }
1328
1329                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
1330                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
1331                                   nla_len(nl_freq), freq_policy);
1332                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
1333                                 continue;
1334                         mode->num_channels++;
1335                 }
1336
1337                 mode->channels = calloc(mode->num_channels, sizeof(struct hostapd_channel_data));
1338                 if (!mode->channels)
1339                         return NL_SKIP;
1340
1341                 idx = 0;
1342
1343                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
1344                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
1345                                   nla_len(nl_freq), freq_policy);
1346                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
1347                                 continue;
1348
1349                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
1350                         mode->channels[idx].flag = 0;
1351
1352                         if (!mode_is_set) {
1353                                 /* crude heuristic */
1354                                 if (mode->channels[idx].freq < 4000)
1355                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
1356                                 else
1357                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
1358                                 mode_is_set = 1;
1359                         }
1360
1361                         /* crude heuristic */
1362                         if (mode->channels[idx].freq < 4000)
1363                                 if (mode->channels[idx].freq == 2848)
1364                                         mode->channels[idx].chan = 14;
1365                                 else
1366                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
1367                         else
1368                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
1369
1370                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
1371                                 mode->channels[idx].flag |=
1372                                         HOSTAPD_CHAN_DISABLED;
1373                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
1374                                 mode->channels[idx].flag |=
1375                                         HOSTAPD_CHAN_PASSIVE_SCAN;
1376                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
1377                                 mode->channels[idx].flag |=
1378                                         HOSTAPD_CHAN_NO_IBSS;
1379                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
1380                                 mode->channels[idx].flag |=
1381                                         HOSTAPD_CHAN_RADAR;
1382
1383                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
1384                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
1385                                 mode->channels[idx].max_tx_power =
1386                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
1387
1388                         idx++;
1389                 }
1390
1391                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
1392                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
1393                                   nla_len(nl_rate), rate_policy);
1394                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
1395                                 continue;
1396                         mode->num_rates++;
1397                 }
1398
1399                 mode->rates = calloc(mode->num_rates, sizeof(struct hostapd_rate_data));
1400                 if (!mode->rates)
1401                         return NL_SKIP;
1402
1403                 idx = 0;
1404
1405                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
1406                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
1407                                   nla_len(nl_rate), rate_policy);
1408                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
1409                                 continue;
1410                         mode->rates[idx].rate = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
1411
1412                         /* crude heuristic */
1413                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
1414                             mode->rates[idx].rate > 200)
1415                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
1416
1417                         if (tb_rate[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE])
1418                                 mode->rates[idx].flags |= HOSTAPD_RATE_PREAMBLE2;
1419
1420                         idx++;
1421                 }
1422         }
1423
1424         return NL_SKIP;
1425 }
1426
1427 static struct hostapd_hw_modes *i802_add_11b(struct hostapd_hw_modes *modes,
1428                                              u16 *num_modes)
1429 {
1430         u16 m;
1431         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
1432         int i, mode11g_idx = -1;
1433
1434         /* If only 802.11g mode is included, use it to construct matching
1435          * 802.11b mode data. */
1436
1437         for (m = 0; m < *num_modes; m++) {
1438                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
1439                         return modes; /* 802.11b already included */
1440                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
1441                         mode11g_idx = m;
1442         }
1443
1444         if (mode11g_idx < 0)
1445                 return modes; /* 2.4 GHz band not supported at all */
1446
1447         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
1448         if (nmodes == NULL)
1449                 return modes; /* Could not add 802.11b mode */
1450
1451         mode = &nmodes[*num_modes];
1452         os_memset(mode, 0, sizeof(*mode));
1453         (*num_modes)++;
1454         modes = nmodes;
1455
1456         mode->mode = HOSTAPD_MODE_IEEE80211B;
1457
1458         mode11g = &modes[mode11g_idx];
1459         mode->num_channels = mode11g->num_channels;
1460         mode->channels = os_malloc(mode11g->num_channels *
1461                                    sizeof(struct hostapd_channel_data));
1462         if (mode->channels == NULL) {
1463                 (*num_modes)--;
1464                 return modes; /* Could not add 802.11b mode */
1465         }
1466         os_memcpy(mode->channels, mode11g->channels,
1467                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
1468
1469         mode->num_rates = 0;
1470         mode->rates = os_malloc(4 * sizeof(struct hostapd_rate_data));
1471         if (mode->rates == NULL) {
1472                 os_free(mode->channels);
1473                 (*num_modes)--;
1474                 return modes; /* Could not add 802.11b mode */
1475         }
1476
1477         for (i = 0; i < mode11g->num_rates; i++) {
1478                 if (mode11g->rates[i].rate > 110 ||
1479                     mode11g->rates[i].flags &
1480                     (HOSTAPD_RATE_ERP | HOSTAPD_RATE_OFDM))
1481                         continue;
1482                 mode->rates[mode->num_rates] = mode11g->rates[i];
1483                 mode->num_rates++;
1484                 if (mode->num_rates == 4)
1485                         break;
1486         }
1487
1488         if (mode->num_rates == 0) {
1489                 os_free(mode->channels);
1490                 os_free(mode->rates);
1491                 (*num_modes)--;
1492                 return modes; /* No 802.11b rates */
1493         }
1494
1495         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
1496                    "information");
1497
1498         return modes;
1499 }
1500
1501 static struct hostapd_hw_modes *i802_get_hw_feature_data(void *priv,
1502                                                          u16 *num_modes,
1503                                                          u16 *flags)
1504 {
1505         struct i802_driver_data *drv = priv;
1506         struct nl_msg *msg;
1507         struct phy_info_arg result = {
1508                 .num_modes = num_modes,
1509                 .modes = NULL,
1510         };
1511
1512         *num_modes = 0;
1513         *flags = 0;
1514
1515         msg = nlmsg_alloc();
1516         if (!msg)
1517                 return NULL;
1518
1519         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1520                     0, NL80211_CMD_GET_WIPHY, 0);
1521
1522         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->iface));
1523
1524         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0)
1525                 return i802_add_11b(result.modes, num_modes);
1526  nla_put_failure:
1527         return NULL;
1528 }
1529
1530
1531 static int i802_set_sta_vlan(void *priv, const u8 *addr,
1532                              const char *ifname, int vlan_id)
1533 {
1534         struct i802_driver_data *drv = priv;
1535         struct nl_msg *msg;
1536
1537         msg = nlmsg_alloc();
1538         if (!msg)
1539                 return -ENOMEM;
1540
1541         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1542                     0, NL80211_CMD_SET_STATION, 0);
1543
1544         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
1545                     if_nametoindex(drv->iface));
1546         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
1547         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
1548                     if_nametoindex(ifname));
1549
1550         return send_and_recv_msgs(drv, msg, NULL, NULL);
1551  nla_put_failure:
1552         return -ENOBUFS;
1553 }
1554
1555
1556 static int i802_set_country(void *priv, const char *country)
1557 {
1558         struct i802_driver_data *drv = priv;
1559         struct nl_msg *msg;
1560         char alpha2[3];
1561
1562         msg = nlmsg_alloc();
1563         if (!msg)
1564                 return -ENOMEM;
1565
1566         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1567                     0, NL80211_CMD_REQ_SET_REG, 0);
1568
1569         alpha2[0] = country[0];
1570         alpha2[1] = country[1];
1571         alpha2[2] = '\0';
1572         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
1573
1574         return send_and_recv_msgs(drv, msg, NULL, NULL);
1575  nla_put_failure:
1576         return -ENOBUFS;
1577 }
1578
1579
1580 static void handle_tx_callback(struct hostapd_data *hapd, u8 *buf, size_t len,
1581                                int ok)
1582 {
1583         struct ieee80211_hdr *hdr;
1584         u16 fc, type, stype;
1585
1586         hdr = (struct ieee80211_hdr *) buf;
1587         fc = le_to_host16(hdr->frame_control);
1588
1589         type = WLAN_FC_GET_TYPE(fc);
1590         stype = WLAN_FC_GET_STYPE(fc);
1591
1592         switch (type) {
1593         case WLAN_FC_TYPE_MGMT:
1594                 wpa_printf(MSG_DEBUG, "MGMT (TX callback) %s",
1595                            ok ? "ACK" : "fail");
1596                 hostapd_mgmt_tx_cb(hapd, buf, len, stype, ok);
1597                 break;
1598         case WLAN_FC_TYPE_CTRL:
1599                 wpa_printf(MSG_DEBUG, "CTRL (TX callback) %s",
1600                            ok ? "ACK" : "fail");
1601                 break;
1602         case WLAN_FC_TYPE_DATA:
1603                 hostapd_tx_status(hapd, hdr->addr1, buf, len, ok);
1604                 break;
1605         default:
1606                 printf("unknown TX callback frame type %d\n", type);
1607                 break;
1608         }
1609 }
1610
1611
1612 static void handle_frame(struct i802_driver_data *drv,
1613                          struct hostapd_iface *iface, u8 *buf, size_t len,
1614                          struct hostapd_frame_info *hfi,
1615                          enum ieee80211_msg_type msg_type)
1616 {
1617         struct ieee80211_hdr *hdr;
1618         u16 fc, type, stype;
1619         size_t data_len = len;
1620         struct hostapd_data *hapd = NULL;
1621         int broadcast_bssid = 0;
1622         size_t i;
1623         u8 *bssid;
1624
1625         /*
1626          * PS-Poll frames are 16 bytes. All other frames are
1627          * 24 bytes or longer.
1628          */
1629         if (len < 16)
1630                 return;
1631
1632         hdr = (struct ieee80211_hdr *) buf;
1633         fc = le_to_host16(hdr->frame_control);
1634
1635         type = WLAN_FC_GET_TYPE(fc);
1636         stype = WLAN_FC_GET_STYPE(fc);
1637
1638         switch (type) {
1639         case WLAN_FC_TYPE_DATA:
1640                 if (len < 24)
1641                         return;
1642                 switch (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) {
1643                 case WLAN_FC_TODS:
1644                         bssid = hdr->addr1;
1645                         break;
1646                 case WLAN_FC_FROMDS:
1647                         bssid = hdr->addr2;
1648                         break;
1649                 default:
1650                         /* discard */
1651                         return;
1652                 }
1653                 break;
1654         case WLAN_FC_TYPE_CTRL:
1655                 /* discard non-ps-poll frames */
1656                 if (stype != WLAN_FC_STYPE_PSPOLL)
1657                         return;
1658                 bssid = hdr->addr1;
1659                 break;
1660         case WLAN_FC_TYPE_MGMT:
1661                 bssid = hdr->addr3;
1662                 break;
1663         default:
1664                 /* discard */
1665                 return;
1666         }
1667
1668         /* find interface frame belongs to */
1669         for (i = 0; i < iface->num_bss; i++) {
1670                 if (memcmp(bssid, iface->bss[i]->own_addr, ETH_ALEN) == 0) {
1671                         hapd = iface->bss[i];
1672                         break;
1673                 }
1674         }
1675
1676         if (hapd == NULL) {
1677                 hapd = iface->bss[0];
1678
1679                 if (bssid[0] != 0xff || bssid[1] != 0xff ||
1680                     bssid[2] != 0xff || bssid[3] != 0xff ||
1681                     bssid[4] != 0xff || bssid[5] != 0xff) {
1682                         /*
1683                          * Unknown BSSID - drop frame if this is not from
1684                          * passive scanning or a beacon (at least ProbeReq
1685                          * frames to other APs may be allowed through RX
1686                          * filtering in the wlan hw/driver)
1687                          */
1688                         if ((type != WLAN_FC_TYPE_MGMT ||
1689                              stype != WLAN_FC_STYPE_BEACON))
1690                                 return;
1691                 } else
1692                         broadcast_bssid = 1;
1693         }
1694
1695         switch (msg_type) {
1696         case ieee80211_msg_normal:
1697                 /* continue processing */
1698                 break;
1699         case ieee80211_msg_tx_callback_ack:
1700                 handle_tx_callback(hapd, buf, data_len, 1);
1701                 return;
1702         case ieee80211_msg_tx_callback_fail:
1703                 handle_tx_callback(hapd, buf, data_len, 0);
1704                 return;
1705         }
1706
1707         switch (type) {
1708         case WLAN_FC_TYPE_MGMT:
1709                 if (stype != WLAN_FC_STYPE_BEACON &&
1710                     stype != WLAN_FC_STYPE_PROBE_REQ)
1711                         wpa_printf(MSG_MSGDUMP, "MGMT");
1712                 if (broadcast_bssid) {
1713                         for (i = 0; i < iface->num_bss; i++)
1714                                 hostapd_mgmt_rx(iface->bss[i], buf, data_len,
1715                                                 stype, hfi);
1716                 } else
1717                         hostapd_mgmt_rx(hapd, buf, data_len, stype, hfi);
1718                 break;
1719         case WLAN_FC_TYPE_CTRL:
1720                 /* can only get here with PS-Poll frames */
1721                 wpa_printf(MSG_DEBUG, "CTRL");
1722                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
1723                 break;
1724         case WLAN_FC_TYPE_DATA:
1725                 hostapd_rx_from_unknown_sta(drv->hapd, hdr->addr2);
1726                 break;
1727         }
1728 }
1729
1730
1731 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
1732 {
1733         struct i802_driver_data *drv = eloop_ctx;
1734         struct sockaddr_ll lladdr;
1735         unsigned char buf[3000];
1736         int len;
1737         socklen_t fromlen = sizeof(lladdr);
1738
1739         len = recvfrom(sock, buf, sizeof(buf), 0,
1740                        (struct sockaddr *)&lladdr, &fromlen);
1741         if (len < 0) {
1742                 perror("recv");
1743                 return;
1744         }
1745
1746         if (have_ifidx(drv, lladdr.sll_ifindex)) {
1747                 struct hostapd_data *hapd;
1748                 hapd = hostapd_sta_get_bss(drv->hapd, lladdr.sll_addr);
1749                 if (!hapd)
1750                         return;
1751                 hostapd_eapol_receive(hapd, lladdr.sll_addr, buf, len);
1752         }
1753 }
1754
1755
1756 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
1757 {
1758         struct i802_driver_data *drv = eloop_ctx;
1759         int len;
1760         unsigned char buf[3000];
1761         struct hostapd_data *hapd = drv->hapd;
1762         struct ieee80211_radiotap_iterator iter;
1763         int ret;
1764         struct hostapd_frame_info hfi;
1765         int injected = 0, failed = 0, msg_type, rxflags = 0;
1766
1767         len = recv(sock, buf, sizeof(buf), 0);
1768         if (len < 0) {
1769                 perror("recv");
1770                 return;
1771         }
1772
1773         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
1774                 printf("received invalid radiotap frame\n");
1775                 return;
1776         }
1777
1778         memset(&hfi, 0, sizeof(hfi));
1779
1780         while (1) {
1781                 ret = ieee80211_radiotap_iterator_next(&iter);
1782                 if (ret == -ENOENT)
1783                         break;
1784                 if (ret) {
1785                         printf("received invalid radiotap frame (%d)\n", ret);
1786                         return;
1787                 }
1788                 switch (iter.this_arg_index) {
1789                 case IEEE80211_RADIOTAP_FLAGS:
1790                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
1791                                 len -= 4;
1792                         break;
1793                 case IEEE80211_RADIOTAP_RX_FLAGS:
1794                         rxflags = 1;
1795                         break;
1796                 case IEEE80211_RADIOTAP_TX_FLAGS:
1797                         injected = 1;
1798                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
1799                                         IEEE80211_RADIOTAP_F_TX_FAIL;
1800                         break;
1801                 case IEEE80211_RADIOTAP_DATA_RETRIES:
1802                         break;
1803                 case IEEE80211_RADIOTAP_CHANNEL:
1804                         /* TODO convert from freq/flags to channel number
1805                         hfi.channel = XXX;
1806                         hfi.phytype = XXX;
1807                          */
1808                         break;
1809                 case IEEE80211_RADIOTAP_RATE:
1810                         hfi.datarate = *iter.this_arg * 5;
1811                         break;
1812                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
1813                         hfi.ssi_signal = *iter.this_arg;
1814                         break;
1815                 }
1816         }
1817
1818         if (rxflags && injected)
1819                 return;
1820
1821         if (!injected)
1822                 msg_type = ieee80211_msg_normal;
1823         else if (failed)
1824                 msg_type = ieee80211_msg_tx_callback_fail;
1825         else
1826                 msg_type = ieee80211_msg_tx_callback_ack;
1827
1828         handle_frame(drv, hapd->iface, buf + iter.max_length,
1829                      len - iter.max_length, &hfi, msg_type);
1830 }
1831
1832
1833 /*
1834  * we post-process the filter code later and rewrite
1835  * this to the offset to the last instruction
1836  */
1837 #define PASS    0xFF
1838 #define FAIL    0xFE
1839
1840 static struct sock_filter msock_filter_insns[] = {
1841         /*
1842          * do a little-endian load of the radiotap length field
1843          */
1844         /* load lower byte into A */
1845         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
1846         /* put it into X (== index register) */
1847         BPF_STMT(BPF_MISC| BPF_TAX, 0),
1848         /* load upper byte into A */
1849         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
1850         /* left-shift it by 8 */
1851         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
1852         /* or with X */
1853         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
1854         /* put result into X */
1855         BPF_STMT(BPF_MISC| BPF_TAX, 0),
1856
1857         /*
1858          * Allow management frames through, this also gives us those
1859          * management frames that we sent ourselves with status
1860          */
1861         /* load the lower byte of the IEEE 802.11 frame control field */
1862         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
1863         /* mask off frame type and version */
1864         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
1865         /* accept frame if it's both 0, fall through otherwise */
1866         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
1867
1868         /*
1869          * TODO: add a bit to radiotap RX flags that indicates
1870          * that the sending station is not associated, then
1871          * add a filter here that filters on our DA and that flag
1872          * to allow us to deauth frames to that bad station.
1873          *
1874          * Not a regression -- we didn't do it before either.
1875          */
1876
1877 #if 0
1878         /*
1879          * drop non-data frames, WDS frames
1880          */
1881         /* load the lower byte of the frame control field */
1882         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
1883         /* mask off QoS bit */
1884         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
1885         /* drop non-data frames */
1886         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
1887         /* load the upper byte of the frame control field */
1888         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
1889         /* mask off toDS/fromDS */
1890         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
1891         /* drop WDS frames */
1892         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, FAIL, 0),
1893 #endif
1894
1895         /*
1896          * add header length to index
1897          */
1898         /* load the lower byte of the frame control field */
1899         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
1900         /* mask off QoS bit */
1901         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
1902         /* right shift it by 6 to give 0 or 2 */
1903         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
1904         /* add data frame header length */
1905         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
1906         /* add index, was start of 802.11 header */
1907         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
1908         /* move to index, now start of LL header */
1909         BPF_STMT(BPF_MISC | BPF_TAX, 0),
1910
1911         /*
1912          * Accept empty data frames, we use those for
1913          * polling activity.
1914          */
1915         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
1916         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
1917
1918         /*
1919          * Accept EAPOL frames
1920          */
1921         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
1922         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
1923         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
1924         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
1925
1926         /* keep these last two statements or change the code below */
1927         /* return 0 == "DROP" */
1928         BPF_STMT(BPF_RET | BPF_K, 0),
1929         /* return ~0 == "keep all" */
1930         BPF_STMT(BPF_RET | BPF_K, ~0),
1931 };
1932
1933 static struct sock_fprog msock_filter = {
1934         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
1935         .filter = msock_filter_insns,
1936 };
1937
1938
1939 static int add_monitor_filter(int s)
1940 {
1941         int idx;
1942
1943         /* rewrite all PASS/FAIL jump offsets */
1944         for (idx = 0; idx < msock_filter.len; idx++) {
1945                 struct sock_filter *insn = &msock_filter_insns[idx];
1946
1947                 if (BPF_CLASS(insn->code) == BPF_JMP) {
1948                         if (insn->code == (BPF_JMP|BPF_JA)) {
1949                                 if (insn->k == PASS)
1950                                         insn->k = msock_filter.len - idx - 2;
1951                                 else if (insn->k == FAIL)
1952                                         insn->k = msock_filter.len - idx - 3;
1953                         }
1954
1955                         if (insn->jt == PASS)
1956                                 insn->jt = msock_filter.len - idx - 2;
1957                         else if (insn->jt == FAIL)
1958                                 insn->jt = msock_filter.len - idx - 3;
1959
1960                         if (insn->jf == PASS)
1961                                 insn->jf = msock_filter.len - idx - 2;
1962                         else if (insn->jf == FAIL)
1963                                 insn->jf = msock_filter.len - idx - 3;
1964                 }
1965         }
1966
1967         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
1968                        &msock_filter, sizeof(msock_filter))) {
1969                 perror("SO_ATTACH_FILTER");
1970                 return -1;
1971         }
1972
1973         return 0;
1974 }
1975
1976
1977 static int nl80211_create_monitor_interface(struct i802_driver_data *drv)
1978 {
1979         char buf[IFNAMSIZ];
1980         struct sockaddr_ll ll;
1981         int optval;
1982         socklen_t optlen;
1983
1984         snprintf(buf, IFNAMSIZ, "mon.%s", drv->iface);
1985         buf[IFNAMSIZ - 1] = '\0';
1986
1987         drv->monitor_ifidx =
1988                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL);
1989
1990         if (drv->monitor_ifidx < 0)
1991                 return -1;
1992
1993         if (hostapd_set_iface_flags(drv, buf, 1))
1994                 goto error;
1995
1996         memset(&ll, 0, sizeof(ll));
1997         ll.sll_family = AF_PACKET;
1998         ll.sll_ifindex = drv->monitor_ifidx;
1999         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
2000         if (drv->monitor_sock < 0) {
2001                 perror("socket[PF_PACKET,SOCK_RAW]");
2002                 goto error;
2003         }
2004
2005         if (add_monitor_filter(drv->monitor_sock)) {
2006                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
2007                            "interface; do filtering in user space");
2008                 /* This works, but will cost in performance. */
2009         }
2010
2011         if (bind(drv->monitor_sock, (struct sockaddr *) &ll,
2012                  sizeof(ll)) < 0) {
2013                 perror("monitor socket bind");
2014                 goto error;
2015         }
2016
2017         optlen = sizeof(optval);
2018         optval = 20;
2019         if (setsockopt
2020             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
2021                 perror("Failed to set socket priority");
2022                 goto error;
2023         }
2024
2025         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
2026                                      drv, NULL)) {
2027                 printf("Could not register monitor read socket\n");
2028                 goto error;
2029         }
2030
2031         return 0;
2032  error:
2033         nl80211_remove_iface(drv, drv->monitor_ifidx);
2034         return -1;
2035 }
2036
2037
2038 static int nl80211_set_mode(struct i802_driver_data *drv, const char *ifname,
2039                             int mode)
2040 {
2041         struct nl_msg *msg;
2042         int ret = -ENOBUFS;
2043
2044         msg = nlmsg_alloc();
2045         if (!msg)
2046                 return -ENOMEM;
2047
2048         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2049                     0, NL80211_CMD_SET_INTERFACE, 0);
2050         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
2051                     if_nametoindex(ifname));
2052         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
2053
2054         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2055         if (!ret)
2056                 return 0;
2057  nla_put_failure:
2058         wpa_printf(MSG_ERROR, "Failed to set interface %s to master "
2059                    "mode.", ifname);
2060         return ret;
2061 }
2062
2063
2064 #ifdef CONFIG_IEEE80211N
2065 static void i802_add_neighbor(struct i802_driver_data *drv, u8 *bssid,
2066                               int freq, u8 *ie, size_t ie_len)
2067 {
2068         struct ieee802_11_elems elems;
2069         int ht, pri_chan = 0, sec_chan = 0;
2070         struct ieee80211_ht_operation *oper;
2071         struct hostapd_neighbor_bss *nnei;
2072
2073         ieee802_11_parse_elems(ie, ie_len, &elems, 0);
2074         ht = elems.ht_capabilities || elems.ht_operation;
2075         if (elems.ht_operation && elems.ht_operation_len >= sizeof(*oper)) {
2076                 oper = (struct ieee80211_ht_operation *) elems.ht_operation;
2077                 pri_chan = oper->control_chan;
2078                 if (oper->ht_param & HT_INFO_HT_PARAM_REC_TRANS_CHNL_WIDTH) {
2079                         if (oper->ht_param &
2080                             HT_INFO_HT_PARAM_SECONDARY_CHNL_ABOVE)
2081                                 sec_chan = pri_chan + 4;
2082                         else if (oper->ht_param &
2083                             HT_INFO_HT_PARAM_SECONDARY_CHNL_BELOW)
2084                                 sec_chan = pri_chan - 4;
2085                 }
2086         }
2087
2088         wpa_printf(MSG_DEBUG, "nl80211: Neighboring BSS - bssid=" MACSTR
2089                    " freq=%d MHz HT=%d pri_chan=%d sec_chan=%d",
2090                    MAC2STR(bssid), freq, ht, pri_chan, sec_chan);
2091
2092         nnei = os_realloc(drv->neighbors, (drv->num_neighbors + 1) *
2093                           sizeof(struct hostapd_neighbor_bss));
2094         if (nnei == NULL)
2095                 return;
2096         drv->neighbors = nnei;
2097         nnei = &nnei[drv->num_neighbors];
2098         os_memcpy(nnei->bssid, bssid, ETH_ALEN);
2099         nnei->freq = freq;
2100         nnei->ht = !!ht;
2101         nnei->pri_chan = pri_chan;
2102         nnei->sec_chan = sec_chan;
2103         drv->num_neighbors++;
2104 }
2105
2106
2107 static int i802_get_scan_freq(struct iw_event *iwe, int *freq)
2108 {
2109         int divi = 1000000, i;
2110
2111         if (iwe->u.freq.e == 0) {
2112                 /*
2113                  * Some drivers do not report frequency, but a channel.
2114                  * Try to map this to frequency by assuming they are using
2115                  * IEEE 802.11b/g.  But don't overwrite a previously parsed
2116                  * frequency if the driver sends both frequency and channel,
2117                  * since the driver may be sending an A-band channel that we
2118                  * don't handle here.
2119                  */
2120
2121                 if (*freq)
2122                         return 0;
2123
2124                 if (iwe->u.freq.m >= 1 && iwe->u.freq.m <= 13) {
2125                         *freq = 2407 + 5 * iwe->u.freq.m;
2126                         return 0;
2127                 } else if (iwe->u.freq.m == 14) {
2128                         *freq = 2484;
2129                         return 0;
2130                 }
2131         }
2132
2133         if (iwe->u.freq.e > 6) {
2134                 wpa_printf(MSG_DEBUG, "Invalid freq in scan results: "
2135                            "m=%d e=%d", iwe->u.freq.m, iwe->u.freq.e);
2136                 return -1;
2137         }
2138
2139         for (i = 0; i < iwe->u.freq.e; i++)
2140                 divi /= 10;
2141         *freq = iwe->u.freq.m / divi;
2142         return 0;
2143 }
2144
2145
2146 static int i802_parse_scan(struct i802_driver_data *drv, u8 *res_buf,
2147                            size_t len)
2148 {
2149         size_t ap_num = 0;
2150         int first;
2151         struct iw_event iwe_buf, *iwe = &iwe_buf;
2152         char *pos, *end, *custom;
2153         u8 bssid[ETH_ALEN];
2154         int freq = 0;
2155         u8 *ie = NULL;
2156         size_t ie_len = 0;
2157
2158         ap_num = 0;
2159         first = 1;
2160
2161         pos = (char *) res_buf;
2162         end = (char *) res_buf + len;
2163
2164         while (pos + IW_EV_LCP_LEN <= end) {
2165                 /* Event data may be unaligned, so make a local, aligned copy
2166                  * before processing. */
2167                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
2168                 if (iwe->len <= IW_EV_LCP_LEN)
2169                         break;
2170
2171                 custom = pos + IW_EV_POINT_LEN;
2172                 if (iwe->cmd == IWEVGENIE) {
2173                         /* WE-19 removed the pointer from struct iw_point */
2174                         char *dpos = (char *) &iwe_buf.u.data.length;
2175                         int dlen = dpos - (char *) &iwe_buf;
2176                         os_memcpy(dpos, pos + IW_EV_LCP_LEN,
2177                                   sizeof(struct iw_event) - dlen);
2178                 } else {
2179                         os_memcpy(&iwe_buf, pos, sizeof(struct iw_event));
2180                         custom += IW_EV_POINT_OFF;
2181                 }
2182
2183                 switch (iwe->cmd) {
2184                 case SIOCGIWAP:
2185                         if (!first)
2186                                 i802_add_neighbor(drv, bssid, freq, ie,
2187                                                   ie_len);
2188                         first = 0;
2189                         os_memcpy(bssid, iwe->u.ap_addr.sa_data, ETH_ALEN);
2190                         freq = 0;
2191                         ie = NULL;
2192                         ie_len = 0;
2193                         break;
2194                 case SIOCGIWFREQ:
2195                         i802_get_scan_freq(iwe, &freq);
2196                         break;
2197                 case IWEVGENIE:
2198                         if (custom + iwe->u.data.length > end) {
2199                                 wpa_printf(MSG_ERROR, "IWEVGENIE overflow");
2200                                 return -1;
2201                         }
2202                         ie = (u8 *) custom;
2203                         ie_len = iwe->u.data.length;
2204                         break;
2205                 }
2206
2207                 pos += iwe->len;
2208         }
2209
2210         if (!first)
2211                 i802_add_neighbor(drv, bssid, freq, ie, ie_len);
2212
2213         return 0;
2214 }
2215
2216
2217 static int i802_get_ht_scan_res(struct i802_driver_data *drv)
2218 {
2219         struct iwreq iwr;
2220         u8 *res_buf;
2221         size_t res_buf_len;
2222         int res;
2223
2224         res_buf_len = IW_SCAN_MAX_DATA;
2225         for (;;) {
2226                 res_buf = os_malloc(res_buf_len);
2227                 if (res_buf == NULL)
2228                         return -1;
2229                 os_memset(&iwr, 0, sizeof(iwr));
2230                 os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
2231                 iwr.u.data.pointer = res_buf;
2232                 iwr.u.data.length = res_buf_len;
2233
2234                 if (ioctl(drv->ioctl_sock, SIOCGIWSCAN, &iwr) == 0)
2235                         break;
2236
2237                 if (errno == E2BIG && res_buf_len < 65535) {
2238                         os_free(res_buf);
2239                         res_buf = NULL;
2240                         res_buf_len *= 2;
2241                         if (res_buf_len > 65535)
2242                                 res_buf_len = 65535; /* 16-bit length field */
2243                         wpa_printf(MSG_DEBUG, "Scan results did not fit - "
2244                                    "trying larger buffer (%lu bytes)",
2245                                    (unsigned long) res_buf_len);
2246                 } else {
2247                         perror("ioctl[SIOCGIWSCAN]");
2248                         os_free(res_buf);
2249                         return -1;
2250                 }
2251         }
2252
2253         if (iwr.u.data.length > res_buf_len) {
2254                 os_free(res_buf);
2255                 return -1;
2256         }
2257
2258         res = i802_parse_scan(drv, res_buf, iwr.u.data.length);
2259         os_free(res_buf);
2260
2261         return res;
2262 }
2263
2264
2265 static int i802_is_event_wireless_scan_complete(char *data, int len)
2266 {
2267         struct iw_event iwe_buf, *iwe = &iwe_buf;
2268         char *pos, *end;
2269
2270         pos = data;
2271         end = data + len;
2272
2273         while (pos + IW_EV_LCP_LEN <= end) {
2274                 /* Event data may be unaligned, so make a local, aligned copy
2275                  * before processing. */
2276                 os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
2277                 if (iwe->cmd == SIOCGIWSCAN)
2278                         return 1;
2279
2280                 pos += iwe->len;
2281         }
2282
2283         return 0;
2284 }
2285
2286
2287 static int i802_is_rtm_scan_complete(int ifindex, struct nlmsghdr *h, int len)
2288 {
2289         struct ifinfomsg *ifi;
2290         int attrlen, _nlmsg_len, rta_len;
2291         struct rtattr *attr;
2292
2293         if (len < (int) sizeof(*ifi))
2294                 return 0;
2295
2296         ifi = NLMSG_DATA(h);
2297
2298         if (ifindex != ifi->ifi_index)
2299                 return 0; /* event for foreign ifindex */
2300
2301         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
2302
2303         attrlen = h->nlmsg_len - _nlmsg_len;
2304         if (attrlen < 0)
2305                 return 0;
2306
2307         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
2308
2309         rta_len = RTA_ALIGN(sizeof(struct rtattr));
2310         while (RTA_OK(attr, attrlen)) {
2311                 if (attr->rta_type == IFLA_WIRELESS &&
2312                     i802_is_event_wireless_scan_complete(
2313                             ((char *) attr) + rta_len,
2314                             attr->rta_len - rta_len))
2315                         return 1;
2316                 attr = RTA_NEXT(attr, attrlen);
2317         }
2318
2319         return 0;
2320 }
2321
2322
2323 static int i802_is_scan_complete(int s, int ifindex)
2324 {
2325         char buf[1024];
2326         int left;
2327         struct nlmsghdr *h;
2328
2329         left = recv(s, buf, sizeof(buf), MSG_DONTWAIT);
2330         if (left < 0) {
2331                 perror("recv(netlink)");
2332                 return 0;
2333         }
2334
2335         h = (struct nlmsghdr *) buf;
2336         while (left >= (int) sizeof(*h)) {
2337                 int len, plen;
2338
2339                 len = h->nlmsg_len;
2340                 plen = len - sizeof(*h);
2341                 if (len > left || plen < 0) {
2342                         wpa_printf(MSG_DEBUG, "Malformed netlink message: "
2343                                    "len=%d left=%d plen=%d",
2344                                    len, left, plen);
2345                         break;
2346                 }
2347
2348                 switch (h->nlmsg_type) {
2349                 case RTM_NEWLINK:
2350                         if (i802_is_rtm_scan_complete(ifindex, h, plen))
2351                                 return 1;
2352                         break;
2353                 }
2354
2355                 len = NLMSG_ALIGN(len);
2356                 left -= len;
2357                 h = (struct nlmsghdr *) ((char *) h + len);
2358         }
2359
2360         return 0;
2361 }
2362
2363
2364 static int i802_ht_scan(struct i802_driver_data *drv)
2365 {
2366         struct iwreq iwr;
2367         int s, res, ifindex;
2368         struct sockaddr_nl local;
2369         time_t now, end;
2370         fd_set rfds;
2371         struct timeval tv;
2372
2373         wpa_printf(MSG_DEBUG, "nl80211: Scanning overlapping BSSes before "
2374                    "starting HT 20/40 MHz BSS");
2375
2376         /* Request a new scan */
2377         /* TODO: would be enough to scan the selected band */
2378         os_memset(&iwr, 0, sizeof(iwr));
2379         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
2380         if (ioctl(drv->ioctl_sock, SIOCSIWSCAN, &iwr) < 0) {
2381                 perror("ioctl[SIOCSIWSCAN]");
2382                 return -1;
2383         }
2384
2385         ifindex = if_nametoindex(drv->iface);
2386
2387         /* Wait for scan completion event or timeout */
2388         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2389         if (s < 0) {
2390                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
2391                 return -1;
2392         }
2393
2394         os_memset(&local, 0, sizeof(local));
2395         local.nl_family = AF_NETLINK;
2396         local.nl_groups = RTMGRP_LINK;
2397         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
2398                 perror("bind(netlink)");
2399                 close(s);
2400                 return -1;
2401         }
2402
2403         time(&end);
2404         end += 30; /* Wait at most 30 seconds for scan results */
2405         for (;;) {
2406                 time(&now);
2407                 tv.tv_sec = end > now ? end - now : 0;
2408                 tv.tv_usec = 0;
2409                 FD_ZERO(&rfds);
2410                 FD_SET(s, &rfds);
2411                 res = select(s + 1, &rfds, NULL, NULL, &tv);
2412                 if (res < 0) {
2413                         perror("select");
2414                         /* Assume results are ready after 10 seconds wait */
2415                         os_sleep(10, 0);
2416                         break;
2417                 } else if (res) {
2418                         if (i802_is_scan_complete(s, ifindex)) {
2419                                 wpa_printf(MSG_DEBUG, "nl80211: Scan "
2420                                            "completed");
2421                                 break;
2422                         }
2423                 } else {
2424                         wpa_printf(MSG_DEBUG, "nl80211: Scan timeout");
2425                         /* Assume results are ready to be read now */
2426                         break;
2427                 }
2428         }
2429
2430         close(s);
2431
2432         return i802_get_ht_scan_res(drv);
2433 }
2434 #endif /* CONFIG_IEEE80211N */
2435
2436
2437 static int i802_init_sockets(struct i802_driver_data *drv, const u8 *bssid)
2438 {
2439         struct ifreq ifr;
2440
2441         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
2442         if (drv->ioctl_sock < 0) {
2443                 perror("socket[PF_INET,SOCK_DGRAM]");
2444                 return -1;
2445         }
2446
2447         /* start listening for EAPOL on the default AP interface */
2448         add_ifidx(drv, if_nametoindex(drv->iface));
2449
2450         if (hostapd_set_iface_flags(drv, drv->iface, 0))
2451                 return -1;
2452
2453         if (bssid) {
2454                 os_strlcpy(ifr.ifr_name, drv->iface, IFNAMSIZ);
2455                 memcpy(ifr.ifr_hwaddr.sa_data, bssid, ETH_ALEN);
2456                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
2457
2458                 if (ioctl(drv->ioctl_sock, SIOCSIFHWADDR, &ifr)) {
2459                         perror("ioctl(SIOCSIFHWADDR)");
2460                         return -1;
2461                 }
2462         }
2463
2464         /*
2465          * initialise generic netlink and nl80211
2466          */
2467         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2468         if (!drv->nl_cb) {
2469                 printf("Failed to allocate netlink callbacks.\n");
2470                 return -1;
2471         }
2472
2473         drv->nl_handle = nl_handle_alloc_cb(drv->nl_cb);
2474         if (!drv->nl_handle) {
2475                 printf("Failed to allocate netlink handle.\n");
2476                 return -1;
2477         }
2478
2479         if (genl_connect(drv->nl_handle)) {
2480                 printf("Failed to connect to generic netlink.\n");
2481                 return -1;
2482         }
2483
2484 #ifdef CONFIG_LIBNL20
2485         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
2486                 printf("Failed to allocate generic netlink cache.\n");
2487                 return -1;
2488         }
2489 #else /* CONFIG_LIBNL20 */
2490         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
2491         if (!drv->nl_cache) {
2492                 printf("Failed to allocate generic netlink cache.\n");
2493                 return -1;
2494         }
2495 #endif /* CONFIG_LIBNL20 */
2496
2497         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
2498         if (!drv->nl80211) {
2499                 printf("nl80211 not found.\n");
2500                 return -1;
2501         }
2502
2503 #ifdef CONFIG_IEEE80211N
2504         if (drv->ht_40mhz_scan) {
2505                 if (nl80211_set_mode(drv, drv->iface, NL80211_IFTYPE_STATION)
2506                     || hostapd_set_iface_flags(drv, drv->iface, 1) ||
2507                     i802_ht_scan(drv) ||
2508                     hostapd_set_iface_flags(drv, drv->iface, 0)) {
2509                         wpa_printf(MSG_ERROR, "Failed to scan channels for "
2510                                    "HT 40 MHz operations");
2511                         return -1;
2512                 }
2513         }
2514 #endif /* CONFIG_IEEE80211N */
2515
2516         /* Initialise a monitor interface */
2517         if (nl80211_create_monitor_interface(drv))
2518                 return -1;
2519
2520         if (nl80211_set_mode(drv, drv->iface, NL80211_IFTYPE_AP))
2521                 goto fail1;
2522
2523         if (hostapd_set_iface_flags(drv, drv->iface, 1))
2524                 goto fail1;
2525
2526         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
2527         if (drv->eapol_sock < 0) {
2528                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
2529                 goto fail1;
2530         }
2531
2532         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
2533         {
2534                 printf("Could not register read socket for eapol\n");
2535                 return -1;
2536         }
2537
2538         memset(&ifr, 0, sizeof(ifr));
2539         os_strlcpy(ifr.ifr_name, drv->iface, sizeof(ifr.ifr_name));
2540         if (ioctl(drv->ioctl_sock, SIOCGIFHWADDR, &ifr) != 0) {
2541                 perror("ioctl(SIOCGIFHWADDR)");
2542                 goto fail1;
2543         }
2544
2545         if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
2546                 printf("Invalid HW-addr family 0x%04x\n",
2547                        ifr.ifr_hwaddr.sa_family);
2548                 goto fail1;
2549         }
2550         memcpy(drv->hapd->own_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
2551
2552         return 0;
2553
2554 fail1:
2555         nl80211_remove_iface(drv, drv->monitor_ifidx);
2556         return -1;
2557 }
2558
2559
2560 static int i802_get_inact_sec(void *priv, const u8 *addr)
2561 {
2562         struct hostap_sta_driver_data data;
2563         int ret;
2564
2565         data.inactive_msec = (unsigned long) -1;
2566         ret = i802_read_sta_data(priv, &data, addr);
2567         if (ret || data.inactive_msec == (unsigned long) -1)
2568                 return -1;
2569         return data.inactive_msec / 1000;
2570 }
2571
2572
2573 static int i802_sta_clear_stats(void *priv, const u8 *addr)
2574 {
2575 #if 0
2576         /* TODO */
2577 #endif
2578         return 0;
2579 }
2580
2581
2582 static void
2583 hostapd_wireless_event_wireless_custom(struct i802_driver_data *drv,
2584                                        char *custom)
2585 {
2586         wpa_printf(MSG_DEBUG, "Custom wireless event: '%s'", custom);
2587
2588         if (strncmp(custom, "MLME-MICHAELMICFAILURE.indication", 33) == 0) {
2589                 char *pos;
2590                 u8 addr[ETH_ALEN];
2591                 pos = strstr(custom, "addr=");
2592                 if (pos == NULL) {
2593                         wpa_printf(MSG_DEBUG,
2594                                    "MLME-MICHAELMICFAILURE.indication "
2595                                    "without sender address ignored");
2596                         return;
2597                 }
2598                 pos += 5;
2599                 if (hwaddr_aton(pos, addr) == 0) {
2600                         hostapd_michael_mic_failure(drv->hapd, addr);
2601                 } else {
2602                         wpa_printf(MSG_DEBUG,
2603                                    "MLME-MICHAELMICFAILURE.indication "
2604                                    "with invalid MAC address");
2605                 }
2606         }
2607 }
2608
2609
2610 static void hostapd_wireless_event_wireless(struct i802_driver_data *drv,
2611                                             char *data, int len)
2612 {
2613         struct iw_event iwe_buf, *iwe = &iwe_buf;
2614         char *pos, *end, *custom, *buf;
2615
2616         pos = data;
2617         end = data + len;
2618
2619         while (pos + IW_EV_LCP_LEN <= end) {
2620                 /* Event data may be unaligned, so make a local, aligned copy
2621                  * before processing. */
2622                 memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
2623                 wpa_printf(MSG_DEBUG, "Wireless event: cmd=0x%x len=%d",
2624                            iwe->cmd, iwe->len);
2625                 if (iwe->len <= IW_EV_LCP_LEN)
2626                         return;
2627
2628                 custom = pos + IW_EV_POINT_LEN;
2629                 if (drv->we_version > 18 &&
2630                     (iwe->cmd == IWEVMICHAELMICFAILURE ||
2631                      iwe->cmd == IWEVCUSTOM)) {
2632                         /* WE-19 removed the pointer from struct iw_point */
2633                         char *dpos = (char *) &iwe_buf.u.data.length;
2634                         int dlen = dpos - (char *) &iwe_buf;
2635                         memcpy(dpos, pos + IW_EV_LCP_LEN,
2636                                sizeof(struct iw_event) - dlen);
2637                 } else {
2638                         memcpy(&iwe_buf, pos, sizeof(struct iw_event));
2639                         custom += IW_EV_POINT_OFF;
2640                 }
2641
2642                 switch (iwe->cmd) {
2643                 case IWEVCUSTOM:
2644                         if (custom + iwe->u.data.length > end)
2645                                 return;
2646                         buf = malloc(iwe->u.data.length + 1);
2647                         if (buf == NULL)
2648                                 return;
2649                         memcpy(buf, custom, iwe->u.data.length);
2650                         buf[iwe->u.data.length] = '\0';
2651                         hostapd_wireless_event_wireless_custom(drv, buf);
2652                         free(buf);
2653                         break;
2654                 }
2655
2656                 pos += iwe->len;
2657         }
2658 }
2659
2660
2661 static void hostapd_wireless_event_rtm_newlink(struct i802_driver_data *drv,
2662                                                struct nlmsghdr *h, int len)
2663 {
2664         struct ifinfomsg *ifi;
2665         int attrlen, _nlmsg_len, rta_len;
2666         struct rtattr *attr;
2667
2668         if (len < (int) sizeof(*ifi))
2669                 return;
2670
2671         ifi = NLMSG_DATA(h);
2672
2673         /* TODO: use ifi->ifi_index to filter out wireless events from other
2674          * interfaces */
2675
2676         _nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
2677
2678         attrlen = h->nlmsg_len - _nlmsg_len;
2679         if (attrlen < 0)
2680                 return;
2681
2682         attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
2683
2684         rta_len = RTA_ALIGN(sizeof(struct rtattr));
2685         while (RTA_OK(attr, attrlen)) {
2686                 if (attr->rta_type == IFLA_WIRELESS) {
2687                         hostapd_wireless_event_wireless(
2688                                 drv, ((char *) attr) + rta_len,
2689                                 attr->rta_len - rta_len);
2690                 }
2691                 attr = RTA_NEXT(attr, attrlen);
2692         }
2693 }
2694
2695
2696 static void hostapd_wireless_event_receive(int sock, void *eloop_ctx,
2697                                            void *sock_ctx)
2698 {
2699         char buf[256];
2700         int left;
2701         struct sockaddr_nl from;
2702         socklen_t fromlen;
2703         struct nlmsghdr *h;
2704         struct i802_driver_data *drv = eloop_ctx;
2705
2706         fromlen = sizeof(from);
2707         left = recvfrom(sock, buf, sizeof(buf), MSG_DONTWAIT,
2708                         (struct sockaddr *) &from, &fromlen);
2709         if (left < 0) {
2710                 if (errno != EINTR && errno != EAGAIN)
2711                         perror("recvfrom(netlink)");
2712                 return;
2713         }
2714
2715         h = (struct nlmsghdr *) buf;
2716         while (left >= (int) sizeof(*h)) {
2717                 int len, plen;
2718
2719                 len = h->nlmsg_len;
2720                 plen = len - sizeof(*h);
2721                 if (len > left || plen < 0) {
2722                         printf("Malformed netlink message: "
2723                                "len=%d left=%d plen=%d\n",
2724                                len, left, plen);
2725                         break;
2726                 }
2727
2728                 switch (h->nlmsg_type) {
2729                 case RTM_NEWLINK:
2730                         hostapd_wireless_event_rtm_newlink(drv, h, plen);
2731                         break;
2732                 }
2733
2734                 len = NLMSG_ALIGN(len);
2735                 left -= len;
2736                 h = (struct nlmsghdr *) ((char *) h + len);
2737         }
2738
2739         if (left > 0) {
2740                 printf("%d extra bytes in the end of netlink message\n", left);
2741         }
2742 }
2743
2744
2745 static int hostap_get_we_version(struct i802_driver_data *drv)
2746 {
2747         struct iw_range *range;
2748         struct iwreq iwr;
2749         int minlen;
2750         size_t buflen;
2751
2752         drv->we_version = 0;
2753
2754         /*
2755          * Use larger buffer than struct iw_range in order to allow the
2756          * structure to grow in the future.
2757          */
2758         buflen = sizeof(struct iw_range) + 500;
2759         range = os_zalloc(buflen);
2760         if (range == NULL)
2761                 return -1;
2762
2763         memset(&iwr, 0, sizeof(iwr));
2764         os_strlcpy(iwr.ifr_name, drv->iface, IFNAMSIZ);
2765         iwr.u.data.pointer = (caddr_t) range;
2766         iwr.u.data.length = buflen;
2767
2768         minlen = ((char *) &range->enc_capa) - (char *) range +
2769                 sizeof(range->enc_capa);
2770
2771         if (ioctl(drv->ioctl_sock, SIOCGIWRANGE, &iwr) < 0) {
2772                 perror("ioctl[SIOCGIWRANGE]");
2773                 free(range);
2774                 return -1;
2775         } else if (iwr.u.data.length >= minlen &&
2776                    range->we_version_compiled >= 18) {
2777                 wpa_printf(MSG_DEBUG, "SIOCGIWRANGE: WE(compiled)=%d "
2778                            "WE(source)=%d enc_capa=0x%x",
2779                            range->we_version_compiled,
2780                            range->we_version_source,
2781                            range->enc_capa);
2782                 drv->we_version = range->we_version_compiled;
2783         }
2784
2785         free(range);
2786         return 0;
2787 }
2788
2789
2790 static int i802_wireless_event_init(struct i802_driver_data *drv)
2791 {
2792         int s;
2793         struct sockaddr_nl local;
2794
2795         hostap_get_we_version(drv);
2796
2797         drv->wext_sock = -1;
2798
2799         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2800         if (s < 0) {
2801                 perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
2802                 return -1;
2803         }
2804
2805         memset(&local, 0, sizeof(local));
2806         local.nl_family = AF_NETLINK;
2807         local.nl_groups = RTMGRP_LINK;
2808         if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
2809                 perror("bind(netlink)");
2810                 close(s);
2811                 return -1;
2812         }
2813
2814         eloop_register_read_sock(s, hostapd_wireless_event_receive, drv,
2815                                  NULL);
2816         drv->wext_sock = s;
2817
2818         return 0;
2819 }
2820
2821
2822 static void i802_wireless_event_deinit(struct i802_driver_data *drv)
2823 {
2824         if (drv->wext_sock < 0)
2825                 return;
2826         eloop_unregister_read_sock(drv->wext_sock);
2827         close(drv->wext_sock);
2828 }
2829
2830
2831 static int i802_sta_deauth(void *priv, const u8 *addr, int reason)
2832 {
2833         struct i802_driver_data *drv = priv;
2834         struct ieee80211_mgmt mgmt;
2835
2836         memset(&mgmt, 0, sizeof(mgmt));
2837         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
2838                                           WLAN_FC_STYPE_DEAUTH);
2839         memcpy(mgmt.da, addr, ETH_ALEN);
2840         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
2841         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
2842         mgmt.u.deauth.reason_code = host_to_le16(reason);
2843         return i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
2844                                       sizeof(mgmt.u.deauth), 0);
2845 }
2846
2847
2848 static int i802_sta_disassoc(void *priv, const u8 *addr, int reason)
2849 {
2850         struct i802_driver_data *drv = priv;
2851         struct ieee80211_mgmt mgmt;
2852
2853         memset(&mgmt, 0, sizeof(mgmt));
2854         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
2855                                           WLAN_FC_STYPE_DISASSOC);
2856         memcpy(mgmt.da, addr, ETH_ALEN);
2857         memcpy(mgmt.sa, drv->hapd->own_addr, ETH_ALEN);
2858         memcpy(mgmt.bssid, drv->hapd->own_addr, ETH_ALEN);
2859         mgmt.u.disassoc.reason_code = host_to_le16(reason);
2860         return  i802_send_mgmt_frame(drv, &mgmt, IEEE80211_HDRLEN +
2861                                        sizeof(mgmt.u.disassoc), 0);
2862 }
2863
2864
2865 static const struct hostapd_neighbor_bss *
2866 i802_get_neighbor_bss(void *priv, size_t *num)
2867 {
2868         struct i802_driver_data *drv = priv;
2869         *num = drv->num_neighbors;
2870         return drv->neighbors;
2871 }
2872
2873
2874 static void *i802_init_bssid(struct hostapd_data *hapd, const u8 *bssid)
2875 {
2876         struct i802_driver_data *drv;
2877
2878         drv = os_zalloc(sizeof(struct i802_driver_data));
2879         if (drv == NULL) {
2880                 printf("Could not allocate memory for i802 driver data\n");
2881                 return NULL;
2882         }
2883
2884         drv->hapd = hapd;
2885         memcpy(drv->iface, hapd->conf->iface, sizeof(drv->iface));
2886         memcpy(drv->bss.iface, hapd->conf->iface, sizeof(drv->iface));
2887
2888         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
2889         drv->if_indices = drv->default_if_indices;
2890         drv->bridge = if_nametoindex(hapd->conf->bridge);
2891         drv->ht_40mhz_scan = hapd->iconf->secondary_channel != 0;
2892
2893         if (i802_init_sockets(drv, bssid))
2894                 goto failed;
2895
2896         if (i802_wireless_event_init(drv))
2897                 goto failed;
2898
2899         return drv;
2900
2901 failed:
2902         free(drv);
2903         return NULL;
2904 }
2905
2906
2907 static void *i802_init(struct hostapd_data *hapd)
2908 {
2909         return i802_init_bssid(hapd, NULL);
2910 }
2911
2912
2913 static void i802_deinit(void *priv)
2914 {
2915         struct i802_driver_data *drv = priv;
2916         struct i802_bss *bss, *prev;
2917
2918         i802_wireless_event_deinit(drv);
2919
2920         if (drv->last_freq_ht) {
2921                 /* Clear HT flags from the driver */
2922                 struct hostapd_freq_params freq;
2923                 os_memset(&freq, 0, sizeof(freq));
2924                 freq.freq = drv->last_freq;
2925                 i802_set_freq(priv, &freq);
2926         }
2927
2928         i802_del_beacon(drv);
2929
2930         /* remove monitor interface */
2931         nl80211_remove_iface(drv, drv->monitor_ifidx);
2932
2933         (void) hostapd_set_iface_flags(drv, drv->iface, 0);
2934
2935         if (drv->monitor_sock >= 0) {
2936                 eloop_unregister_read_sock(drv->monitor_sock);
2937                 close(drv->monitor_sock);
2938         }
2939         if (drv->ioctl_sock >= 0)
2940                 close(drv->ioctl_sock);
2941         if (drv->eapol_sock >= 0) {
2942                 eloop_unregister_read_sock(drv->eapol_sock);
2943                 close(drv->eapol_sock);
2944         }
2945
2946         genl_family_put(drv->nl80211);
2947         nl_cache_free(drv->nl_cache);
2948         nl_handle_destroy(drv->nl_handle);
2949         nl_cb_put(drv->nl_cb);
2950
2951         if (drv->if_indices != drv->default_if_indices)
2952                 free(drv->if_indices);
2953
2954         os_free(drv->neighbors);
2955
2956         bss = drv->bss.next;
2957         while (bss) {
2958                 prev = bss;
2959                 bss = bss->next;
2960                 os_free(bss);
2961         }
2962
2963         free(drv);
2964 }
2965
2966
2967 const struct hapd_driver_ops wpa_driver_nl80211_ops = {
2968         .name = "nl80211",
2969         .init = i802_init,
2970         .init_bssid = i802_init_bssid,
2971         .deinit = i802_deinit,
2972         .set_key = i802_set_key,
2973         .get_seqnum = i802_get_seqnum,
2974         .flush = i802_flush,
2975         .read_sta_data = i802_read_sta_data,
2976         .send_eapol = i802_send_eapol,
2977         .sta_set_flags = i802_sta_set_flags,
2978         .sta_deauth = i802_sta_deauth,
2979         .sta_disassoc = i802_sta_disassoc,
2980         .sta_remove = i802_sta_remove,
2981         .send_mgmt_frame = i802_send_mgmt_frame,
2982         .sta_add = i802_sta_add,
2983         .get_inact_sec = i802_get_inact_sec,
2984         .sta_clear_stats = i802_sta_clear_stats,
2985         .set_freq = i802_set_freq,
2986         .set_rts = i802_set_rts,
2987         .set_frag = i802_set_frag,
2988         .set_retry = i802_set_retry,
2989         .set_rate_sets = i802_set_rate_sets,
2990         .set_beacon = i802_set_beacon,
2991         .set_beacon_int = i802_set_beacon_int,
2992         .set_cts_protect = i802_set_cts_protect,
2993         .set_preamble = i802_set_preamble,
2994         .set_short_slot_time = i802_set_short_slot_time,
2995         .set_tx_queue_params = i802_set_tx_queue_params,
2996         .bss_add = i802_bss_add,
2997         .bss_remove = i802_bss_remove,
2998         .if_add = i802_if_add,
2999         .if_update = i802_if_update,
3000         .if_remove = i802_if_remove,
3001         .get_hw_feature_data = i802_get_hw_feature_data,
3002         .set_sta_vlan = i802_set_sta_vlan,
3003         .set_country = i802_set_country,
3004         .get_neighbor_bss = i802_get_neighbor_bss,
3005 };