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