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