xref: /openbsd-src/sys/net80211/ieee80211_node.c (revision d59bb9942320b767f2a19aaa7690c8c6e30b724c)
1 /*	$OpenBSD: ieee80211_node.c,v 1.115 2017/03/04 12:44:27 stsp Exp $	*/
2 /*	$NetBSD: ieee80211_node.c,v 1.14 2004/05/09 09:18:47 dyoung Exp $	*/
3 
4 /*-
5  * Copyright (c) 2001 Atsushi Onoe
6  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
7  * Copyright (c) 2008 Damien Bergamini
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include "bridge.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/mbuf.h>
38 #include <sys/malloc.h>
39 #include <sys/kernel.h>
40 #include <sys/socket.h>
41 #include <sys/sockio.h>
42 #include <sys/endian.h>
43 #include <sys/errno.h>
44 #include <sys/sysctl.h>
45 #include <sys/tree.h>
46 
47 #include <net/if.h>
48 #include <net/if_dl.h>
49 #include <net/if_media.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/if_ether.h>
53 
54 #if NBRIDGE > 0
55 #include <net/if_bridge.h>
56 #endif
57 
58 #include <net80211/ieee80211_var.h>
59 #include <net80211/ieee80211_priv.h>
60 
61 struct ieee80211_node *ieee80211_node_alloc(struct ieee80211com *);
62 void ieee80211_node_free(struct ieee80211com *, struct ieee80211_node *);
63 void ieee80211_node_copy(struct ieee80211com *, struct ieee80211_node *,
64     const struct ieee80211_node *);
65 void ieee80211_choose_rsnparams(struct ieee80211com *);
66 u_int8_t ieee80211_node_getrssi(struct ieee80211com *,
67     const struct ieee80211_node *);
68 void ieee80211_setup_node(struct ieee80211com *, struct ieee80211_node *,
69     const u_int8_t *);
70 void ieee80211_free_node(struct ieee80211com *, struct ieee80211_node *);
71 void ieee80211_ba_del(struct ieee80211_node *);
72 struct ieee80211_node *ieee80211_alloc_node_helper(struct ieee80211com *);
73 void ieee80211_node_cleanup(struct ieee80211com *, struct ieee80211_node *);
74 void ieee80211_needs_auth(struct ieee80211com *, struct ieee80211_node *);
75 #ifndef IEEE80211_STA_ONLY
76 void ieee80211_node_join_ht(struct ieee80211com *, struct ieee80211_node *);
77 void ieee80211_node_join_rsn(struct ieee80211com *, struct ieee80211_node *);
78 void ieee80211_node_join_11g(struct ieee80211com *, struct ieee80211_node *);
79 void ieee80211_node_leave_ht(struct ieee80211com *, struct ieee80211_node *);
80 void ieee80211_node_leave_rsn(struct ieee80211com *, struct ieee80211_node *);
81 void ieee80211_node_leave_11g(struct ieee80211com *, struct ieee80211_node *);
82 void ieee80211_inact_timeout(void *);
83 void ieee80211_node_cache_timeout(void *);
84 #endif
85 
86 #ifndef IEEE80211_STA_ONLY
87 void
88 ieee80211_inact_timeout(void *arg)
89 {
90 	struct ieee80211com *ic = arg;
91 	struct ieee80211_node *ni, *next_ni;
92 	int s;
93 
94 	s = splnet();
95 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
96 	    ni != NULL; ni = next_ni) {
97 		next_ni = RBT_NEXT(ieee80211_tree, ni);
98 		if (ni->ni_refcnt > 0)
99 			continue;
100 		if (ni->ni_inact < IEEE80211_INACT_MAX)
101 			ni->ni_inact++;
102 	}
103 	splx(s);
104 
105 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
106 }
107 
108 void
109 ieee80211_node_cache_timeout(void *arg)
110 {
111 	struct ieee80211com *ic = arg;
112 
113 	ieee80211_clean_nodes(ic, 1);
114 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
115 }
116 #endif
117 
118 void
119 ieee80211_node_attach(struct ifnet *ifp)
120 {
121 	struct ieee80211com *ic = (void *)ifp;
122 #ifndef IEEE80211_STA_ONLY
123 	int size;
124 #endif
125 
126 	RBT_INIT(ieee80211_tree, &ic->ic_tree);
127 	ic->ic_node_alloc = ieee80211_node_alloc;
128 	ic->ic_node_free = ieee80211_node_free;
129 	ic->ic_node_copy = ieee80211_node_copy;
130 	ic->ic_node_getrssi = ieee80211_node_getrssi;
131 	ic->ic_scangen = 1;
132 	ic->ic_max_nnodes = ieee80211_cache_size;
133 
134 	if (ic->ic_max_aid == 0)
135 		ic->ic_max_aid = IEEE80211_AID_DEF;
136 	else if (ic->ic_max_aid > IEEE80211_AID_MAX)
137 		ic->ic_max_aid = IEEE80211_AID_MAX;
138 #ifndef IEEE80211_STA_ONLY
139 	size = howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t);
140 	ic->ic_aid_bitmap = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
141 	if (ic->ic_aid_bitmap == NULL) {
142 		/* XXX no way to recover */
143 		printf("%s: no memory for AID bitmap!\n", __func__);
144 		ic->ic_max_aid = 0;
145 	}
146 	if (ic->ic_caps & (IEEE80211_C_HOSTAP | IEEE80211_C_IBSS)) {
147 		ic->ic_tim_len = howmany(ic->ic_max_aid, 8);
148 		ic->ic_tim_bitmap = malloc(ic->ic_tim_len, M_DEVBUF,
149 		    M_NOWAIT | M_ZERO);
150 		if (ic->ic_tim_bitmap == NULL) {
151 			printf("%s: no memory for TIM bitmap!\n", __func__);
152 			ic->ic_tim_len = 0;
153 		} else
154 			ic->ic_set_tim = ieee80211_set_tim;
155 		timeout_set(&ic->ic_rsn_timeout,
156 		    ieee80211_gtk_rekey_timeout, ic);
157 		timeout_set(&ic->ic_inact_timeout,
158 		    ieee80211_inact_timeout, ic);
159 		timeout_set(&ic->ic_node_cache_timeout,
160 		    ieee80211_node_cache_timeout, ic);
161 	}
162 #endif
163 }
164 
165 struct ieee80211_node *
166 ieee80211_alloc_node_helper(struct ieee80211com *ic)
167 {
168 	struct ieee80211_node *ni;
169 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
170 		ieee80211_clean_nodes(ic, 0);
171 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
172 		return NULL;
173 	ni = (*ic->ic_node_alloc)(ic);
174 	return ni;
175 }
176 
177 void
178 ieee80211_node_lateattach(struct ifnet *ifp)
179 {
180 	struct ieee80211com *ic = (void *)ifp;
181 	struct ieee80211_node *ni;
182 
183 	ni = ieee80211_alloc_node_helper(ic);
184 	if (ni == NULL)
185 		panic("unable to setup inital BSS node");
186 	ni->ni_chan = IEEE80211_CHAN_ANYC;
187 	ic->ic_bss = ieee80211_ref_node(ni);
188 	ic->ic_txpower = IEEE80211_TXPOWER_MAX;
189 #ifndef IEEE80211_STA_ONLY
190 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
191 #endif
192 }
193 
194 void
195 ieee80211_node_detach(struct ifnet *ifp)
196 {
197 	struct ieee80211com *ic = (void *)ifp;
198 
199 	if (ic->ic_bss != NULL) {
200 		(*ic->ic_node_free)(ic, ic->ic_bss);
201 		ic->ic_bss = NULL;
202 	}
203 	ieee80211_free_allnodes(ic);
204 #ifndef IEEE80211_STA_ONLY
205 	if (ic->ic_aid_bitmap != NULL)
206 		free(ic->ic_aid_bitmap, M_DEVBUF, 0);
207 	if (ic->ic_tim_bitmap != NULL)
208 		free(ic->ic_tim_bitmap, M_DEVBUF, 0);
209 	timeout_del(&ic->ic_inact_timeout);
210 	timeout_del(&ic->ic_node_cache_timeout);
211 	timeout_del(&ic->ic_tkip_micfail_timeout);
212 #endif
213 	timeout_del(&ic->ic_rsn_timeout);
214 }
215 
216 /*
217  * AP scanning support.
218  */
219 
220 /*
221  * Initialize the active channel set based on the set
222  * of available channels and the current PHY mode.
223  */
224 void
225 ieee80211_reset_scan(struct ifnet *ifp)
226 {
227 	struct ieee80211com *ic = (void *)ifp;
228 
229 	memcpy(ic->ic_chan_scan, ic->ic_chan_active,
230 		sizeof(ic->ic_chan_active));
231 	/* NB: hack, setup so next_scan starts with the first channel */
232 	if (ic->ic_bss != NULL && ic->ic_bss->ni_chan == IEEE80211_CHAN_ANYC)
233 		ic->ic_bss->ni_chan = &ic->ic_channels[IEEE80211_CHAN_MAX];
234 }
235 
236 /*
237  * Begin an active scan.
238  */
239 void
240 ieee80211_begin_scan(struct ifnet *ifp)
241 {
242 	struct ieee80211com *ic = (void *)ifp;
243 
244 	if (ic->ic_scan_lock & IEEE80211_SCAN_LOCKED)
245 		return;
246 	ic->ic_scan_lock |= IEEE80211_SCAN_LOCKED;
247 
248 	/*
249 	 * In all but hostap mode scanning starts off in
250 	 * an active mode before switching to passive.
251 	 */
252 #ifndef IEEE80211_STA_ONLY
253 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
254 #endif
255 	{
256 		ic->ic_flags |= IEEE80211_F_ASCAN;
257 		ic->ic_stats.is_scan_active++;
258 	}
259 #ifndef IEEE80211_STA_ONLY
260 	else
261 		ic->ic_stats.is_scan_passive++;
262 #endif
263 	if (ifp->if_flags & IFF_DEBUG)
264 		printf("%s: begin %s scan\n", ifp->if_xname,
265 			(ic->ic_flags & IEEE80211_F_ASCAN) ?
266 				"active" : "passive");
267 
268 	/*
269 	 * Flush any previously seen AP's. Note that the latter
270 	 * assumes we don't act as both an AP and a station,
271 	 * otherwise we'll potentially flush state of stations
272 	 * associated with us.
273 	 */
274 	ieee80211_free_allnodes(ic);
275 
276 	/*
277 	 * Reset the current mode. Setting the current mode will also
278 	 * reset scan state.
279 	 */
280 	if (IFM_MODE(ic->ic_media.ifm_cur->ifm_media) == IFM_AUTO)
281 		ic->ic_curmode = IEEE80211_MODE_AUTO;
282 	ieee80211_setmode(ic, ic->ic_curmode);
283 
284 	ic->ic_scan_count = 0;
285 
286 	/* Scan the next channel. */
287 	ieee80211_next_scan(ifp);
288 }
289 
290 /*
291  * Switch to the next channel marked for scanning.
292  */
293 void
294 ieee80211_next_scan(struct ifnet *ifp)
295 {
296 	struct ieee80211com *ic = (void *)ifp;
297 	struct ieee80211_channel *chan;
298 
299 	chan = ic->ic_bss->ni_chan;
300 	for (;;) {
301 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
302 			chan = &ic->ic_channels[0];
303 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
304 			/*
305 			 * Ignore channels marked passive-only
306 			 * during an active scan.
307 			 */
308 			if ((ic->ic_flags & IEEE80211_F_ASCAN) == 0 ||
309 			    (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
310 				break;
311 		}
312 		if (chan == ic->ic_bss->ni_chan) {
313 			ieee80211_end_scan(ifp);
314 			return;
315 		}
316 	}
317 	clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
318 	DPRINTF(("chan %d->%d\n",
319 	    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
320 	    ieee80211_chan2ieee(ic, chan)));
321 	ic->ic_bss->ni_chan = chan;
322 	ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
323 }
324 
325 #ifndef IEEE80211_STA_ONLY
326 void
327 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
328 {
329 	struct ieee80211_node *ni;
330 	struct ifnet *ifp = &ic->ic_if;
331 
332 	ni = ic->ic_bss;
333 	if (ifp->if_flags & IFF_DEBUG)
334 		printf("%s: creating ibss\n", ifp->if_xname);
335 	ic->ic_flags |= IEEE80211_F_SIBSS;
336 	ni->ni_chan = chan;
337 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, ni->ni_chan)];
338 	ni->ni_txrate = 0;
339 	IEEE80211_ADDR_COPY(ni->ni_macaddr, ic->ic_myaddr);
340 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
341 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
342 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) != 0)
343 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
344 		else
345 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
346 	}
347 	ni->ni_esslen = ic->ic_des_esslen;
348 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
349 	ni->ni_rssi = 0;
350 	ni->ni_rstamp = 0;
351 	memset(ni->ni_tstamp, 0, sizeof(ni->ni_tstamp));
352 	ni->ni_intval = ic->ic_lintval;
353 	ni->ni_capinfo = IEEE80211_CAPINFO_IBSS;
354 	if (ic->ic_flags & IEEE80211_F_WEPON)
355 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
356 	if (ic->ic_flags & IEEE80211_F_HTON) {
357 		const struct ieee80211_edca_ac_params *ac_qap;
358 		struct ieee80211_edca_ac_params *ac;
359 		int aci;
360 
361 		/*
362 		 * Default to non-member HT protection. This will be updated
363 		 * later based on the number of non-HT nodes in the node cache.
364 		 */
365 		ni->ni_htop1 = IEEE80211_HTPROT_NONMEMBER;
366 		ic->ic_protmode = IEEE80211_PROT_RTSCTS;
367 
368 		/* Configure QoS EDCA parameters. */
369 		for (aci = 0; aci < EDCA_NUM_AC; aci++) {
370 			ac = &ic->ic_edca_ac[aci];
371 			ac_qap = &ieee80211_qap_edca_table[ic->ic_curmode][aci];
372 			ac->ac_acm       = ac_qap->ac_acm;
373 			ac->ac_aifsn     = ac_qap->ac_aifsn;
374 			ac->ac_ecwmin    = ac_qap->ac_ecwmin;
375 			ac->ac_ecwmax    = ac_qap->ac_ecwmax;
376 			ac->ac_txoplimit = ac_qap->ac_txoplimit;
377 		}
378 		if (ic->ic_updateedca)
379 			(*ic->ic_updateedca)(ic);
380 	}
381 	if (ic->ic_flags & IEEE80211_F_RSNON) {
382 		struct ieee80211_key *k;
383 
384 		/* initialize 256-bit global key counter to a random value */
385 		arc4random_buf(ic->ic_globalcnt, EAPOL_KEY_NONCE_LEN);
386 
387 		ni->ni_rsnprotos = ic->ic_rsnprotos;
388 		ni->ni_rsnakms = ic->ic_rsnakms;
389 		ni->ni_rsnciphers = ic->ic_rsnciphers;
390 		ni->ni_rsngroupcipher = ic->ic_rsngroupcipher;
391 		ni->ni_rsngroupmgmtcipher = ic->ic_rsngroupmgmtcipher;
392 		ni->ni_rsncaps = 0;
393 		if (ic->ic_caps & IEEE80211_C_MFP) {
394 			ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPC;
395 			if (ic->ic_flags & IEEE80211_F_MFPR)
396 				ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPR;
397 		}
398 
399 		ic->ic_def_txkey = 1;
400 		ic->ic_flags &= ~IEEE80211_F_COUNTERM;
401 		k = &ic->ic_nw_keys[ic->ic_def_txkey];
402 		memset(k, 0, sizeof(*k));
403 		k->k_id = ic->ic_def_txkey;
404 		k->k_cipher = ni->ni_rsngroupcipher;
405 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
406 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
407 		arc4random_buf(k->k_key, k->k_len);
408 		(*ic->ic_set_key)(ic, ni, k);	/* XXX */
409 
410 		if (ic->ic_caps & IEEE80211_C_MFP) {
411 			ic->ic_igtk_kid = 4;
412 			k = &ic->ic_nw_keys[ic->ic_igtk_kid];
413 			memset(k, 0, sizeof(*k));
414 			k->k_id = ic->ic_igtk_kid;
415 			k->k_cipher = ni->ni_rsngroupmgmtcipher;
416 			k->k_flags = IEEE80211_KEY_IGTK | IEEE80211_KEY_TX;
417 			k->k_len = 16;
418 			arc4random_buf(k->k_key, k->k_len);
419 			(*ic->ic_set_key)(ic, ni, k);	/* XXX */
420 		}
421 		/*
422 		 * In HostAP mode, multicast traffic is sent using ic_bss
423 		 * as the Tx node, so mark our node as valid so we can send
424 		 * multicast frames using the group key we've just configured.
425 		 */
426 		ni->ni_port_valid = 1;
427 		ni->ni_flags |= IEEE80211_NODE_TXPROT;
428 
429 		/* schedule a GTK/IGTK rekeying after 3600s */
430 		timeout_add_sec(&ic->ic_rsn_timeout, 3600);
431 	}
432 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
433 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
434 	ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
435 }
436 #endif	/* IEEE80211_STA_ONLY */
437 
438 int
439 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
440 {
441 	u_int8_t rate;
442 	int fail;
443 
444 	fail = 0;
445 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
446 		fail |= 0x01;
447 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
448 	    ni->ni_chan != ic->ic_des_chan)
449 		fail |= 0x01;
450 #ifndef IEEE80211_STA_ONLY
451 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
452 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
453 			fail |= 0x02;
454 	} else
455 #endif
456 	{
457 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
458 			fail |= 0x02;
459 	}
460 	if (ic->ic_flags & (IEEE80211_F_WEPON | IEEE80211_F_RSNON)) {
461 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
462 			fail |= 0x04;
463 	} else {
464 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
465 			fail |= 0x04;
466 	}
467 
468 	rate = ieee80211_fix_rate(ic, ni, IEEE80211_F_DONEGO);
469 	if (rate & IEEE80211_RATE_BASIC)
470 		fail |= 0x08;
471 	if (ic->ic_des_esslen != 0 &&
472 	    (ni->ni_esslen != ic->ic_des_esslen ||
473 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
474 		fail |= 0x10;
475 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
476 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
477 		fail |= 0x20;
478 
479 	if (ic->ic_flags & IEEE80211_F_RSNON) {
480 		/*
481 		 * If at least one RSN IE field from the AP's RSN IE fails
482 		 * to overlap with any value the STA supports, the STA shall
483 		 * decline to associate with that AP.
484 		 */
485 		if ((ni->ni_rsnprotos & ic->ic_rsnprotos) == 0)
486 			fail |= 0x40;
487 		if ((ni->ni_rsnakms & ic->ic_rsnakms) == 0)
488 			fail |= 0x40;
489 		if ((ni->ni_rsnakms & ic->ic_rsnakms &
490 		     ~(IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK)) == 0) {
491 			/* AP only supports PSK AKMPs */
492 			if (!(ic->ic_flags & IEEE80211_F_PSK))
493 				fail |= 0x40;
494 		}
495 		if (ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP40 &&
496 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_TKIP &&
497 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_CCMP &&
498 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP104)
499 			fail |= 0x40;
500 		if ((ni->ni_rsnciphers & ic->ic_rsnciphers) == 0)
501 			fail |= 0x40;
502 
503 		/* we only support BIP as the IGTK cipher */
504 		if ((ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC) &&
505 		    ni->ni_rsngroupmgmtcipher != IEEE80211_CIPHER_BIP)
506 			fail |= 0x40;
507 
508 		/* we do not support MFP but AP requires it */
509 		if (!(ic->ic_caps & IEEE80211_C_MFP) &&
510 		    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPR))
511 			fail |= 0x40;
512 
513 		/* we require MFP but AP does not support it */
514 		if ((ic->ic_caps & IEEE80211_C_MFP) &&
515 		    (ic->ic_flags & IEEE80211_F_MFPR) &&
516 		    !(ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
517 			fail |= 0x40;
518 	}
519 
520 #ifdef IEEE80211_DEBUG
521 	if (ic->ic_if.if_flags & IFF_DEBUG) {
522 		printf(" %c %s", fail ? '-' : '+',
523 		    ether_sprintf(ni->ni_macaddr));
524 		printf(" %s%c", ether_sprintf(ni->ni_bssid),
525 		    fail & 0x20 ? '!' : ' ');
526 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
527 			fail & 0x01 ? '!' : ' ');
528 		printf(" %+4d", ni->ni_rssi);
529 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
530 		    fail & 0x08 ? '!' : ' ');
531 		printf(" %4s%c",
532 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
533 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
534 		    "????",
535 		    fail & 0x02 ? '!' : ' ');
536 		printf(" %7s%c ",
537 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
538 		    "privacy" : "no",
539 		    fail & 0x04 ? '!' : ' ');
540 		printf(" %3s%c ",
541 		    (ic->ic_flags & IEEE80211_F_RSNON) ?
542 		    "rsn" : "no",
543 		    fail & 0x40 ? '!' : ' ');
544 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
545 		printf("%s\n", fail & 0x10 ? "!" : "");
546 	}
547 #endif
548 	return fail;
549 }
550 
551 /*
552  * Complete a scan of potential channels.
553  */
554 void
555 ieee80211_end_scan(struct ifnet *ifp)
556 {
557 	struct ieee80211com *ic = (void *)ifp;
558 	struct ieee80211_node *ni, *nextbs, *selbs;
559 
560 	if (ifp->if_flags & IFF_DEBUG)
561 		printf("%s: end %s scan\n", ifp->if_xname,
562 			(ic->ic_flags & IEEE80211_F_ASCAN) ?
563 				"active" : "passive");
564 
565 	if (ic->ic_scan_count)
566 		ic->ic_flags &= ~IEEE80211_F_ASCAN;
567 
568 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
569 
570 #ifndef IEEE80211_STA_ONLY
571 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
572 		/* XXX off stack? */
573 		u_char occupied[howmany(IEEE80211_CHAN_MAX, NBBY)];
574 		int i, fail;
575 
576 		/*
577 		 * The passive scan to look for existing AP's completed,
578 		 * select a channel to camp on.  Identify the channels
579 		 * that already have one or more AP's and try to locate
580 		 * an unoccupied one.  If that fails, pick a random
581 		 * channel from the active set.
582 		 */
583 		memset(occupied, 0, sizeof(occupied));
584 		RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
585 			setbit(occupied, ieee80211_chan2ieee(ic, ni->ni_chan));
586 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
587 			if (isset(ic->ic_chan_active, i) && isclr(occupied, i))
588 				break;
589 		if (i == IEEE80211_CHAN_MAX) {
590 			fail = arc4random() & 3;	/* random 0-3 */
591 			for (i = 0; i < IEEE80211_CHAN_MAX; i++)
592 				if (isset(ic->ic_chan_active, i) && fail-- == 0)
593 					break;
594 		}
595 		ieee80211_create_ibss(ic, &ic->ic_channels[i]);
596 		goto wakeup;
597 	}
598 #endif
599 	if (ni == NULL) {
600 		DPRINTF(("no scan candidate\n"));
601  notfound:
602 
603 #ifndef IEEE80211_STA_ONLY
604 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
605 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
606 		    ic->ic_des_esslen != 0) {
607 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
608 			goto wakeup;
609 		}
610 #endif
611 		/*
612 		 * Scan the next mode if nothing has been found. This
613 		 * is necessary if the device supports different
614 		 * incompatible modes in the same channel range, like
615 		 * like 11b and "pure" 11G mode.
616 		 * If the device scans all bands in one fell swoop, return
617 		 * current scan results to userspace regardless of mode.
618 		 * This will loop forever except for user-initiated scans.
619 		 */
620 		if (ieee80211_next_mode(ifp) == IEEE80211_MODE_AUTO ||
621 		    (ic->ic_caps & IEEE80211_C_SCANALLBAND)) {
622 			if (ic->ic_scan_lock & IEEE80211_SCAN_REQUEST &&
623 			    ic->ic_scan_lock & IEEE80211_SCAN_RESUME) {
624 				ic->ic_scan_lock = IEEE80211_SCAN_LOCKED;
625 				/* Return from a user-initiated scan. */
626 				wakeup(&ic->ic_scan_lock);
627 			} else if (ic->ic_scan_lock & IEEE80211_SCAN_REQUEST)
628 				goto wakeup;
629 			ic->ic_scan_count++;
630 		}
631 
632 		/*
633 		 * Reset the list of channels to scan and start again.
634 		 */
635 		ieee80211_next_scan(ifp);
636 		return;
637 	}
638 	selbs = NULL;
639 
640 	for (; ni != NULL; ni = nextbs) {
641 		nextbs = RBT_NEXT(ieee80211_tree, ni);
642 		if (ni->ni_fails) {
643 			/*
644 			 * The configuration of the access points may change
645 			 * during my scan.  So delete the entry for the AP
646 			 * and retry to associate if there is another beacon.
647 			 */
648 			if (ni->ni_fails++ > 2)
649 				ieee80211_free_node(ic, ni);
650 			continue;
651 		}
652 		if (ieee80211_match_bss(ic, ni) != 0)
653 			continue;
654 
655 		/* Pick the AP/IBSS match with the best RSSI. */
656 		if (selbs == NULL)
657 			selbs = ni;
658 		else if ((ic->ic_caps & IEEE80211_C_SCANALLBAND) &&
659 		    IEEE80211_IS_CHAN_5GHZ(selbs->ni_chan) &&
660 		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan) &&
661 		    selbs->ni_rssi >= (ic->ic_max_rssi - (ic->ic_max_rssi / 4)))
662 			/*
663 			 * Prefer 5GHz (with reasonable RSSI) over 2GHz since
664 			 * the 5GHz band is usually less saturated.
665 			 */
666 			continue;
667 		else if (ni->ni_rssi > selbs->ni_rssi)
668 			selbs = ni;
669 	}
670 	if (selbs == NULL)
671 		goto notfound;
672 	(*ic->ic_node_copy)(ic, ic->ic_bss, selbs);
673 	ni = ic->ic_bss;
674 
675 	ic->ic_curmode = ieee80211_chan2mode(ic, ni->ni_chan);
676 
677 	/* Make sure we send valid rates in an association request. */
678 	if (ic->ic_opmode == IEEE80211_M_STA)
679 		ieee80211_fix_rate(ic, ni,
680 		    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
681 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
682 
683 	if (ic->ic_flags & IEEE80211_F_RSNON)
684 		ieee80211_choose_rsnparams(ic);
685 	else if (ic->ic_flags & IEEE80211_F_WEPON)
686 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
687 
688 	ieee80211_node_newstate(selbs, IEEE80211_STA_BSS);
689 #ifndef IEEE80211_STA_ONLY
690 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
691 		ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
692 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
693 		if (ni->ni_rates.rs_nrates == 0)
694 			goto notfound;
695 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
696 	} else
697 #endif
698 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
699 
700  wakeup:
701 	if (ic->ic_scan_lock & IEEE80211_SCAN_REQUEST) {
702 		/* Return from a user-initiated scan. */
703 		wakeup(&ic->ic_scan_lock);
704 	}
705 
706 	ic->ic_scan_lock = IEEE80211_SCAN_UNLOCKED;
707 }
708 
709 /*
710  * Autoselect the best RSN parameters (protocol, AKMP, pairwise cipher...)
711  * that are supported by both peers (STA mode only).
712  */
713 void
714 ieee80211_choose_rsnparams(struct ieee80211com *ic)
715 {
716 	struct ieee80211_node *ni = ic->ic_bss;
717 	struct ieee80211_pmk *pmk;
718 
719 	/* filter out unsupported protocol versions */
720 	ni->ni_rsnprotos &= ic->ic_rsnprotos;
721 	/* prefer RSN (aka WPA2) over WPA */
722 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
723 		ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
724 	else
725 		ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
726 
727 	/* filter out unsupported AKMPs */
728 	ni->ni_rsnakms &= ic->ic_rsnakms;
729 	/* prefer SHA-256 based AKMPs */
730 	if ((ic->ic_flags & IEEE80211_F_PSK) && (ni->ni_rsnakms &
731 	    (IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK))) {
732 		/* AP supports PSK AKMP and a PSK is configured */
733 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_PSK)
734 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_PSK;
735 		else
736 			ni->ni_rsnakms = IEEE80211_AKM_PSK;
737 	} else {
738 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_8021X)
739 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_8021X;
740 		else
741 			ni->ni_rsnakms = IEEE80211_AKM_8021X;
742 		/* check if we have a cached PMK for this AP */
743 		if (ni->ni_rsnprotos == IEEE80211_PROTO_RSN &&
744 		    (pmk = ieee80211_pmksa_find(ic, ni, NULL)) != NULL) {
745 			memcpy(ni->ni_pmkid, pmk->pmk_pmkid,
746 			    IEEE80211_PMKID_LEN);
747 			ni->ni_flags |= IEEE80211_NODE_PMKID;
748 		}
749 	}
750 
751 	/* filter out unsupported pairwise ciphers */
752 	ni->ni_rsnciphers &= ic->ic_rsnciphers;
753 	/* prefer CCMP over TKIP */
754 	if (ni->ni_rsnciphers & IEEE80211_CIPHER_CCMP)
755 		ni->ni_rsnciphers = IEEE80211_CIPHER_CCMP;
756 	else
757 		ni->ni_rsnciphers = IEEE80211_CIPHER_TKIP;
758 	ni->ni_rsncipher = ni->ni_rsnciphers;
759 
760 	/* use MFP if we both support it */
761 	if ((ic->ic_caps & IEEE80211_C_MFP) &&
762 	    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
763 		ni->ni_flags |= IEEE80211_NODE_MFP;
764 }
765 
766 int
767 ieee80211_get_rate(struct ieee80211com *ic)
768 {
769 	u_int8_t (*rates)[IEEE80211_RATE_MAXSIZE];
770 	int rate;
771 
772 	rates = &ic->ic_bss->ni_rates.rs_rates;
773 
774 	if (ic->ic_fixed_rate != -1)
775 		rate = (*rates)[ic->ic_fixed_rate];
776 	else if (ic->ic_state == IEEE80211_S_RUN)
777 		rate = (*rates)[ic->ic_bss->ni_txrate];
778 	else
779 		rate = 0;
780 
781 	return rate & IEEE80211_RATE_VAL;
782 }
783 
784 struct ieee80211_node *
785 ieee80211_node_alloc(struct ieee80211com *ic)
786 {
787 	return malloc(sizeof(struct ieee80211_node), M_DEVBUF,
788 	    M_NOWAIT | M_ZERO);
789 }
790 
791 void
792 ieee80211_node_cleanup(struct ieee80211com *ic, struct ieee80211_node *ni)
793 {
794 	if (ni->ni_rsnie != NULL) {
795 		free(ni->ni_rsnie, M_DEVBUF, 0);
796 		ni->ni_rsnie = NULL;
797 	}
798 	ieee80211_ba_del(ni);
799 }
800 
801 void
802 ieee80211_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
803 {
804 	ieee80211_node_cleanup(ic, ni);
805 	free(ni, M_DEVBUF, 0);
806 }
807 
808 void
809 ieee80211_node_copy(struct ieee80211com *ic,
810 	struct ieee80211_node *dst, const struct ieee80211_node *src)
811 {
812 	ieee80211_node_cleanup(ic, dst);
813 	*dst = *src;
814 	dst->ni_rsnie = NULL;
815 	if (src->ni_rsnie != NULL)
816 		ieee80211_save_ie(src->ni_rsnie, &dst->ni_rsnie);
817 }
818 
819 u_int8_t
820 ieee80211_node_getrssi(struct ieee80211com *ic,
821     const struct ieee80211_node *ni)
822 {
823 	return ni->ni_rssi;
824 }
825 
826 void
827 ieee80211_setup_node(struct ieee80211com *ic,
828 	struct ieee80211_node *ni, const u_int8_t *macaddr)
829 {
830 	int s;
831 
832 	DPRINTF(("%s\n", ether_sprintf((u_int8_t *)macaddr)));
833 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
834 	ieee80211_node_newstate(ni, IEEE80211_STA_CACHE);
835 
836 	ni->ni_ic = ic;	/* back-pointer */
837 #ifndef IEEE80211_STA_ONLY
838 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
839 	timeout_set(&ni->ni_eapol_to, ieee80211_eapol_timeout, ni);
840 	timeout_set(&ni->ni_sa_query_to, ieee80211_sa_query_timeout, ni);
841 #endif
842 	s = splnet();
843 	RBT_INSERT(ieee80211_tree, &ic->ic_tree, ni);
844 	ic->ic_nnodes++;
845 	splx(s);
846 }
847 
848 struct ieee80211_node *
849 ieee80211_alloc_node(struct ieee80211com *ic, const u_int8_t *macaddr)
850 {
851 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
852 	if (ni != NULL)
853 		ieee80211_setup_node(ic, ni, macaddr);
854 	else
855 		ic->ic_stats.is_rx_nodealloc++;
856 	return ni;
857 }
858 
859 struct ieee80211_node *
860 ieee80211_dup_bss(struct ieee80211com *ic, const u_int8_t *macaddr)
861 {
862 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
863 	if (ni != NULL) {
864 		ieee80211_setup_node(ic, ni, macaddr);
865 		/*
866 		 * Inherit from ic_bss.
867 		 */
868 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
869 		ni->ni_chan = ic->ic_bss->ni_chan;
870 	} else
871 		ic->ic_stats.is_rx_nodealloc++;
872 	return ni;
873 }
874 
875 struct ieee80211_node *
876 ieee80211_find_node(struct ieee80211com *ic, const u_int8_t *macaddr)
877 {
878 	struct ieee80211_node *ni;
879 	int cmp;
880 
881 	/* similar to RBT_FIND except we compare keys, not nodes */
882 	ni = RBT_ROOT(ieee80211_tree, &ic->ic_tree);
883 	while (ni != NULL) {
884 		cmp = memcmp(macaddr, ni->ni_macaddr, IEEE80211_ADDR_LEN);
885 		if (cmp < 0)
886 			ni = RBT_LEFT(ieee80211_tree, ni);
887 		else if (cmp > 0)
888 			ni = RBT_RIGHT(ieee80211_tree, ni);
889 		else
890 			break;
891 	}
892 	return ni;
893 }
894 
895 /*
896  * Return a reference to the appropriate node for sending
897  * a data frame.  This handles node discovery in adhoc networks.
898  *
899  * Drivers will call this, so increase the reference count before
900  * returning the node.
901  */
902 struct ieee80211_node *
903 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
904 {
905 #ifndef IEEE80211_STA_ONLY
906 	struct ieee80211_node *ni;
907 	int s;
908 #endif
909 
910 	/*
911 	 * The destination address should be in the node table
912 	 * unless we are operating in station mode or this is a
913 	 * multicast/broadcast frame.
914 	 */
915 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
916 		return ieee80211_ref_node(ic->ic_bss);
917 
918 #ifndef IEEE80211_STA_ONLY
919 	s = splnet();
920 	ni = ieee80211_find_node(ic, macaddr);
921 	splx(s);
922 	if (ni == NULL) {
923 		if (ic->ic_opmode != IEEE80211_M_IBSS &&
924 		    ic->ic_opmode != IEEE80211_M_AHDEMO)
925 			return NULL;
926 
927 		/*
928 		 * Fake up a node; this handles node discovery in
929 		 * adhoc mode.  Note that for the driver's benefit
930 		 * we we treat this like an association so the driver
931 		 * has an opportunity to setup its private state.
932 		 *
933 		 * XXX need better way to handle this; issue probe
934 		 *     request so we can deduce rate set, etc.
935 		 */
936 		if ((ni = ieee80211_dup_bss(ic, macaddr)) == NULL)
937 			return NULL;
938 		/* XXX no rate negotiation; just dup */
939 		ni->ni_rates = ic->ic_bss->ni_rates;
940 		ni->ni_txrate = 0;
941 		if (ic->ic_newassoc)
942 			(*ic->ic_newassoc)(ic, ni, 1);
943 	}
944 	return ieee80211_ref_node(ni);
945 #else
946 	return NULL;	/* can't get there */
947 #endif	/* IEEE80211_STA_ONLY */
948 }
949 
950 /*
951  * It is usually desirable to process a Rx packet using its sender's
952  * node-record instead of the BSS record.
953  *
954  * - AP mode: keep a node-record for every authenticated/associated
955  *   station *in the BSS*. For future use, we also track neighboring
956  *   APs, since they might belong to the same ESS.  APs in the same
957  *   ESS may bridge packets to each other, forming a Wireless
958  *   Distribution System (WDS).
959  *
960  * - IBSS mode: keep a node-record for every station *in the BSS*.
961  *   Also track neighboring stations by their beacons/probe responses.
962  *
963  * - monitor mode: keep a node-record for every sender, regardless
964  *   of BSS.
965  *
966  * - STA mode: the only available node-record is the BSS record,
967  *   ic->ic_bss.
968  *
969  * Of all the 802.11 Control packets, only the node-records for
970  * RTS packets node-record can be looked up.
971  *
972  * Return non-zero if the packet's node-record is kept, zero
973  * otherwise.
974  */
975 static __inline int
976 ieee80211_needs_rxnode(struct ieee80211com *ic,
977     const struct ieee80211_frame *wh, const u_int8_t **bssid)
978 {
979 	int monitor, rc = 0;
980 
981 	monitor = (ic->ic_opmode == IEEE80211_M_MONITOR);
982 
983 	*bssid = NULL;
984 
985 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
986 	case IEEE80211_FC0_TYPE_CTL:
987 		if (!monitor)
988 			break;
989 		return (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
990 		    IEEE80211_FC0_SUBTYPE_RTS;
991 	case IEEE80211_FC0_TYPE_MGT:
992 		*bssid = wh->i_addr3;
993 		switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
994 		case IEEE80211_FC0_SUBTYPE_BEACON:
995 		case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
996 			break;
997 		default:
998 #ifndef IEEE80211_STA_ONLY
999 			if (ic->ic_opmode == IEEE80211_M_STA)
1000 				break;
1001 			rc = IEEE80211_ADDR_EQ(*bssid, ic->ic_bss->ni_bssid) ||
1002 			     IEEE80211_ADDR_EQ(*bssid, etherbroadcastaddr);
1003 #endif
1004 			break;
1005 		}
1006 		break;
1007 	case IEEE80211_FC0_TYPE_DATA:
1008 		switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
1009 		case IEEE80211_FC1_DIR_NODS:
1010 			*bssid = wh->i_addr3;
1011 #ifndef IEEE80211_STA_ONLY
1012 			if (ic->ic_opmode == IEEE80211_M_IBSS ||
1013 			    ic->ic_opmode == IEEE80211_M_AHDEMO)
1014 				rc = IEEE80211_ADDR_EQ(*bssid,
1015 				    ic->ic_bss->ni_bssid);
1016 #endif
1017 			break;
1018 		case IEEE80211_FC1_DIR_TODS:
1019 			*bssid = wh->i_addr1;
1020 #ifndef IEEE80211_STA_ONLY
1021 			if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1022 				rc = IEEE80211_ADDR_EQ(*bssid,
1023 				    ic->ic_bss->ni_bssid);
1024 #endif
1025 			break;
1026 		case IEEE80211_FC1_DIR_FROMDS:
1027 		case IEEE80211_FC1_DIR_DSTODS:
1028 			*bssid = wh->i_addr2;
1029 #ifndef IEEE80211_STA_ONLY
1030 			rc = (ic->ic_opmode == IEEE80211_M_HOSTAP);
1031 #endif
1032 			break;
1033 		}
1034 		break;
1035 	}
1036 	return monitor || rc;
1037 }
1038 
1039 /*
1040  * Drivers call this, so increase the reference count before returning
1041  * the node.
1042  */
1043 struct ieee80211_node *
1044 ieee80211_find_rxnode(struct ieee80211com *ic,
1045     const struct ieee80211_frame *wh)
1046 {
1047 	static const u_int8_t zero[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1048 	struct ieee80211_node *ni;
1049 	const u_int8_t *bssid;
1050 	int s;
1051 
1052 	if (!ieee80211_needs_rxnode(ic, wh, &bssid))
1053 		return ieee80211_ref_node(ic->ic_bss);
1054 
1055 	s = splnet();
1056 	ni = ieee80211_find_node(ic, wh->i_addr2);
1057 	splx(s);
1058 
1059 	if (ni != NULL)
1060 		return ieee80211_ref_node(ni);
1061 #ifndef IEEE80211_STA_ONLY
1062 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1063 		return ieee80211_ref_node(ic->ic_bss);
1064 #endif
1065 	/* XXX see remarks in ieee80211_find_txnode */
1066 	/* XXX no rate negotiation; just dup */
1067 	if ((ni = ieee80211_dup_bss(ic, wh->i_addr2)) == NULL)
1068 		return ieee80211_ref_node(ic->ic_bss);
1069 
1070 	IEEE80211_ADDR_COPY(ni->ni_bssid, (bssid != NULL) ? bssid : zero);
1071 
1072 	ni->ni_rates = ic->ic_bss->ni_rates;
1073 	ni->ni_txrate = 0;
1074 	if (ic->ic_newassoc)
1075 		(*ic->ic_newassoc)(ic, ni, 1);
1076 
1077 	DPRINTF(("faked-up node %p for %s\n", ni,
1078 	    ether_sprintf((u_int8_t *)wh->i_addr2)));
1079 
1080 	return ieee80211_ref_node(ni);
1081 }
1082 
1083 struct ieee80211_node *
1084 ieee80211_find_node_for_beacon(struct ieee80211com *ic,
1085     const u_int8_t *macaddr, const struct ieee80211_channel *chan,
1086     const char *ssid, u_int8_t rssi)
1087 {
1088 	struct ieee80211_node *ni, *keep = NULL;
1089 	int s, score = 0;
1090 
1091 	if ((ni = ieee80211_find_node(ic, macaddr)) != NULL) {
1092 		s = splnet();
1093 
1094 		if (ni->ni_chan != chan && ni->ni_rssi >= rssi)
1095 			score++;
1096 		if (ssid[1] == 0 && ni->ni_esslen != 0)
1097 			score++;
1098 		if (score > 0)
1099 			keep = ni;
1100 
1101 		splx(s);
1102 	}
1103 
1104 	return (keep);
1105 }
1106 
1107 void
1108 ieee80211_ba_del(struct ieee80211_node *ni)
1109 {
1110 	int tid;
1111 
1112 	for (tid = 0; tid < nitems(ni->ni_rx_ba); tid++) {
1113 		struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
1114 		if (ba->ba_state != IEEE80211_BA_INIT) {
1115 			if (timeout_pending(&ba->ba_to))
1116 				timeout_del(&ba->ba_to);
1117 			if (timeout_pending(&ba->ba_gap_to))
1118 				timeout_del(&ba->ba_gap_to);
1119 			ba->ba_state = IEEE80211_BA_INIT;
1120 		}
1121 	}
1122 
1123 	for (tid = 0; tid < nitems(ni->ni_tx_ba); tid++) {
1124 		struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
1125 		if (ba->ba_state != IEEE80211_BA_INIT) {
1126 			if (timeout_pending(&ba->ba_to))
1127 				timeout_del(&ba->ba_to);
1128 			ba->ba_state = IEEE80211_BA_INIT;
1129 		}
1130 	}
1131 }
1132 
1133 void
1134 ieee80211_free_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1135 {
1136 	if (ni == ic->ic_bss)
1137 		panic("freeing bss node");
1138 
1139 	splassert(IPL_NET);
1140 
1141 	DPRINTF(("%s\n", ether_sprintf(ni->ni_macaddr)));
1142 #ifndef IEEE80211_STA_ONLY
1143 	timeout_del(&ni->ni_eapol_to);
1144 	timeout_del(&ni->ni_sa_query_to);
1145 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1146 #endif
1147 	ieee80211_ba_del(ni);
1148 	RBT_REMOVE(ieee80211_tree, &ic->ic_tree, ni);
1149 	ic->ic_nnodes--;
1150 #ifndef IEEE80211_STA_ONLY
1151 	if (mq_purge(&ni->ni_savedq) > 0) {
1152 		if (ic->ic_set_tim != NULL)
1153 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
1154 	}
1155 #endif
1156 	(*ic->ic_node_free)(ic, ni);
1157 	/* TBD indicate to drivers that a new node can be allocated */
1158 }
1159 
1160 void
1161 ieee80211_release_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1162 {
1163 	int s;
1164 
1165 	DPRINTF(("%s refcnt %u\n", ether_sprintf(ni->ni_macaddr),
1166 	    ni->ni_refcnt));
1167 	s = splnet();
1168 	if (ieee80211_node_decref(ni) == 0 &&
1169 	    ni->ni_state == IEEE80211_STA_COLLECT) {
1170 		ieee80211_free_node(ic, ni);
1171 	}
1172 	splx(s);
1173 }
1174 
1175 void
1176 ieee80211_free_allnodes(struct ieee80211com *ic)
1177 {
1178 	struct ieee80211_node *ni;
1179 	int s;
1180 
1181 	DPRINTF(("freeing all nodes\n"));
1182 	s = splnet();
1183 	while ((ni = RBT_MIN(ieee80211_tree, &ic->ic_tree)) != NULL)
1184 		ieee80211_free_node(ic, ni);
1185 	splx(s);
1186 
1187 	if (ic->ic_bss != NULL)
1188 		ieee80211_node_cleanup(ic, ic->ic_bss);	/* for station mode */
1189 }
1190 
1191 void
1192 ieee80211_clean_cached(struct ieee80211com *ic)
1193 {
1194 	struct ieee80211_node *ni, *next_ni;
1195 	int s;
1196 
1197 	s = splnet();
1198 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1199 	    ni != NULL; ni = next_ni) {
1200 		next_ni = RBT_NEXT(ieee80211_tree, ni);
1201 		if (ni->ni_state == IEEE80211_STA_CACHE)
1202 			ieee80211_free_node(ic, ni);
1203 	}
1204 	splx(s);
1205 }
1206 /*
1207  * Timeout inactive nodes.
1208  *
1209  * If called because of a cache timeout, which happens only in hostap and ibss
1210  * modes, clean all inactive cached or authenticated nodes but don't de-auth
1211  * any associated nodes. Also update HT protection settings.
1212  *
1213  * Else, this function is called because a new node must be allocated but the
1214  * node cache is full. In this case, return as soon as a free slot was made
1215  * available. If acting as hostap, clean cached nodes regardless of their
1216  * recent activity and also allow de-authing of authenticated nodes older
1217  * than one cache wait interval, and de-authing of inactive associated nodes.
1218  */
1219 void
1220 ieee80211_clean_nodes(struct ieee80211com *ic, int cache_timeout)
1221 {
1222 	struct ieee80211_node *ni, *next_ni;
1223 	u_int gen = ic->ic_scangen++;		/* NB: ok 'cuz single-threaded*/
1224 	int s;
1225 #ifndef IEEE80211_STA_ONLY
1226 	int nnodes = 0, nonht = 0, nonhtassoc = 0;
1227 	struct ifnet *ifp = &ic->ic_if;
1228 	enum ieee80211_htprot htprot = IEEE80211_HTPROT_NONE;
1229 	enum ieee80211_protmode protmode = IEEE80211_PROT_NONE;
1230 #endif
1231 
1232 	s = splnet();
1233 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1234 	    ni != NULL; ni = next_ni) {
1235 		next_ni = RBT_NEXT(ieee80211_tree, ni);
1236 		if (!cache_timeout && ic->ic_nnodes < ic->ic_max_nnodes)
1237 			break;
1238 		if (ni->ni_scangen == gen)	/* previously handled */
1239 			continue;
1240 #ifndef IEEE80211_STA_ONLY
1241 		nnodes++;
1242 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
1243 			if ((ni->ni_rxmcs[0] & 0xff) == 0) {
1244 				nonht++;
1245 				if (ni->ni_state == IEEE80211_STA_ASSOC)
1246 					nonhtassoc++;
1247 			}
1248 		}
1249 #endif
1250 		ni->ni_scangen = gen;
1251 		if (ni->ni_refcnt > 0)
1252 			continue;
1253 #ifndef IEEE80211_STA_ONLY
1254 		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
1255 		    ic->ic_opmode == IEEE80211_M_IBSS) &&
1256 		    ic->ic_state == IEEE80211_S_RUN) {
1257 			if (cache_timeout) {
1258 				if (ni->ni_state != IEEE80211_STA_COLLECT &&
1259 				    (ni->ni_state == IEEE80211_STA_ASSOC ||
1260 				    ni->ni_inact < IEEE80211_INACT_MAX))
1261 					continue;
1262 			} else {
1263 				if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1264 				    ((ni->ni_state == IEEE80211_STA_ASSOC &&
1265 				    ni->ni_inact < IEEE80211_INACT_MAX) ||
1266 				    (ni->ni_state == IEEE80211_STA_AUTH &&
1267 				     ni->ni_inact == 0)))
1268 				    	continue;
1269 
1270 				if (ic->ic_opmode == IEEE80211_M_IBSS &&
1271 				    ni->ni_state != IEEE80211_STA_COLLECT &&
1272 				    ni->ni_state != IEEE80211_STA_CACHE &&
1273 				    ni->ni_inact < IEEE80211_INACT_MAX)
1274 					continue;
1275 			}
1276 		}
1277 		if (ifp->if_flags & IFF_DEBUG)
1278 			printf("%s: station %s purged from node cache\n",
1279 			    ifp->if_xname, ether_sprintf(ni->ni_macaddr));
1280 #endif
1281 		/*
1282 		 * If we're hostap and the node is authenticated, send
1283 		 * a deauthentication frame. The node will be freed when
1284 		 * the driver calls ieee80211_release_node().
1285 		 */
1286 #ifndef IEEE80211_STA_ONLY
1287 		nnodes--;
1288 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
1289 			if ((ni->ni_rxmcs[0] & 0xff) == 0) {
1290 				nonht--;
1291 				if (ni->ni_state == IEEE80211_STA_ASSOC)
1292 					nonhtassoc--;
1293 			}
1294 		}
1295 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1296 		    ni->ni_state >= IEEE80211_STA_AUTH &&
1297 		    ni->ni_state != IEEE80211_STA_COLLECT) {
1298 			IEEE80211_SEND_MGMT(ic, ni,
1299 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
1300 			    IEEE80211_REASON_AUTH_EXPIRE);
1301 			ieee80211_node_leave(ic, ni);
1302 		} else
1303 #endif
1304 			ieee80211_free_node(ic, ni);
1305 		ic->ic_stats.is_node_timeout++;
1306 	}
1307 
1308 #ifndef IEEE80211_STA_ONLY
1309 	if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
1310 		/* Update HT protection settings. */
1311 		if (nonht) {
1312 			protmode = IEEE80211_PROT_RTSCTS;
1313 			if (nonhtassoc)
1314 				htprot = IEEE80211_HTPROT_NONHT_MIXED;
1315 			else
1316 				htprot = IEEE80211_HTPROT_NONMEMBER;
1317 		}
1318 		if (ic->ic_bss->ni_htop1 != htprot) {
1319 			ic->ic_bss->ni_htop1 = htprot;
1320 			ic->ic_protmode = protmode;
1321 			if (ic->ic_update_htprot)
1322 				ic->ic_update_htprot(ic, ic->ic_bss);
1323 		}
1324 	}
1325 
1326 	/*
1327 	 * During a cache timeout we iterate over all nodes.
1328 	 * Check for node leaks by comparing the actual number of cached
1329 	 * nodes with the ic_nnodes count, which is maintained while adding
1330 	 * and removing nodes from the cache.
1331 	 */
1332 	if ((ifp->if_flags & IFF_DEBUG) && cache_timeout &&
1333 	    nnodes != ic->ic_nnodes)
1334 		printf("%s: number of cached nodes is %d, expected %d,"
1335 		    "possible nodes leak\n", ifp->if_xname, nnodes,
1336 		    ic->ic_nnodes);
1337 #endif
1338 	splx(s);
1339 }
1340 
1341 void
1342 ieee80211_iterate_nodes(struct ieee80211com *ic, ieee80211_iter_func *f,
1343     void *arg)
1344 {
1345 	struct ieee80211_node *ni;
1346 	int s;
1347 
1348 	s = splnet();
1349 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
1350 		(*f)(arg, ni);
1351 	splx(s);
1352 }
1353 
1354 
1355 /*
1356  * Install received HT caps information in the node's state block.
1357  */
1358 void
1359 ieee80211_setup_htcaps(struct ieee80211_node *ni, const uint8_t *data,
1360     uint8_t len)
1361 {
1362 	uint16_t rxrate;
1363 
1364 	if (len != 26)
1365 		return;
1366 
1367 	ni->ni_htcaps = (data[0] | (data[1] << 8));
1368 	ni->ni_ampdu_param = data[2];
1369 
1370 	memcpy(ni->ni_rxmcs, &data[3], sizeof(ni->ni_rxmcs));
1371 	/* clear reserved bits */
1372 	clrbit(ni->ni_rxmcs, 77);
1373 	clrbit(ni->ni_rxmcs, 78);
1374 	clrbit(ni->ni_rxmcs, 79);
1375 
1376 	/* Max MCS Rx rate in 1Mb/s units (0 means "not specified"). */
1377 	rxrate = ((data[13] | (data[14]) << 8) & IEEE80211_MCS_RX_RATE_HIGH);
1378 	if (rxrate < 1024)
1379 		ni->ni_max_rxrate = rxrate;
1380 
1381 	ni->ni_tx_mcs_set = data[15];
1382 	ni->ni_htxcaps = (data[19] | (data[20] << 8));
1383 	ni->ni_txbfcaps = (data[21] | (data[22] << 8) | (data[23] << 16) |
1384 		(data[24] << 24));
1385 	ni->ni_aselcaps = data[25];
1386 }
1387 
1388 #ifndef IEEE80211_STA_ONLY
1389 /*
1390  * Handle nodes switching from 11n into legacy modes.
1391  */
1392 void
1393 ieee80211_clear_htcaps(struct ieee80211_node *ni)
1394 {
1395 	ni->ni_htcaps = 0;
1396 	ni->ni_ampdu_param = 0;
1397 	memset(ni->ni_rxmcs, 0, sizeof(ni->ni_rxmcs));
1398 	ni->ni_max_rxrate = 0;
1399 	ni->ni_tx_mcs_set = 0;
1400 	ni->ni_htxcaps = 0;
1401 	ni->ni_txbfcaps = 0;
1402 	ni->ni_aselcaps = 0;
1403 
1404 	ni->ni_flags &= ~IEEE80211_NODE_HT;
1405 
1406 }
1407 #endif
1408 
1409 /*
1410  * Install received HT op information in the node's state block.
1411  */
1412 int
1413 ieee80211_setup_htop(struct ieee80211_node *ni, const uint8_t *data,
1414     uint8_t len)
1415 {
1416 	if (len != 22)
1417 		return 0;
1418 
1419 	ni->ni_primary_chan = data[0]; /* XXX corresponds to ni_chan */
1420 
1421 	ni->ni_htop0 = data[1];
1422 	ni->ni_htop1 = (data[2] | (data[3] << 8));
1423 	ni->ni_htop2 = (data[3] | (data[4] << 8));
1424 
1425 	memcpy(ni->ni_basic_mcs, &data[6], sizeof(ni->ni_basic_mcs));
1426 
1427 	return 1;
1428 }
1429 
1430 /*
1431  * Install received rate set information in the node's state block.
1432  */
1433 int
1434 ieee80211_setup_rates(struct ieee80211com *ic, struct ieee80211_node *ni,
1435     const u_int8_t *rates, const u_int8_t *xrates, int flags)
1436 {
1437 	struct ieee80211_rateset *rs = &ni->ni_rates;
1438 
1439 	memset(rs, 0, sizeof(*rs));
1440 	rs->rs_nrates = rates[1];
1441 	memcpy(rs->rs_rates, rates + 2, rs->rs_nrates);
1442 	if (xrates != NULL) {
1443 		u_int8_t nxrates;
1444 		/*
1445 		 * Tack on 11g extended supported rate element.
1446 		 */
1447 		nxrates = xrates[1];
1448 		if (rs->rs_nrates + nxrates > IEEE80211_RATE_MAXSIZE) {
1449 			nxrates = IEEE80211_RATE_MAXSIZE - rs->rs_nrates;
1450 			DPRINTF(("extended rate set too large; "
1451 			    "only using %u of %u rates\n",
1452 			    nxrates, xrates[1]));
1453 			ic->ic_stats.is_rx_rstoobig++;
1454 		}
1455 		memcpy(rs->rs_rates + rs->rs_nrates, xrates+2, nxrates);
1456 		rs->rs_nrates += nxrates;
1457 	}
1458 	return ieee80211_fix_rate(ic, ni, flags);
1459 }
1460 
1461 #ifndef IEEE80211_STA_ONLY
1462 /*
1463  * Check if the specified node supports ERP.
1464  */
1465 int
1466 ieee80211_iserp_sta(const struct ieee80211_node *ni)
1467 {
1468 	static const u_int8_t rates[] = { 2, 4, 11, 22, 12, 24, 48 };
1469 	const struct ieee80211_rateset *rs = &ni->ni_rates;
1470 	int i, j;
1471 
1472 	/*
1473 	 * A STA supports ERP operation if it includes all the Clause 19
1474 	 * mandatory rates in its supported rate set.
1475 	 */
1476 	for (i = 0; i < nitems(rates); i++) {
1477 		for (j = 0; j < rs->rs_nrates; j++) {
1478 			if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == rates[i])
1479 				break;
1480 		}
1481 		if (j == rs->rs_nrates)
1482 			return 0;
1483 	}
1484 	return 1;
1485 }
1486 
1487 /*
1488  * This function is called to notify the 802.1X PACP machine that a new
1489  * 802.1X port is enabled and must be authenticated. For 802.11, a port
1490  * becomes enabled whenever a STA successfully completes Open System
1491  * authentication with an AP.
1492  */
1493 void
1494 ieee80211_needs_auth(struct ieee80211com *ic, struct ieee80211_node *ni)
1495 {
1496 	/*
1497 	 * XXX this could be done via the route socket of via a dedicated
1498 	 * EAP socket or another kernel->userland notification mechanism.
1499 	 * The notification should include the MAC address (ni_macaddr).
1500 	 */
1501 }
1502 
1503 /*
1504  * Handle an HT STA joining an HT network.
1505  */
1506 void
1507 ieee80211_node_join_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
1508 {
1509 	enum ieee80211_htprot;
1510 
1511 	/* Update HT protection setting. */
1512 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0) {
1513 		ic->ic_bss->ni_htop1 = IEEE80211_HTPROT_NONHT_MIXED;
1514 		if (ic->ic_update_htprot)
1515 			ic->ic_update_htprot(ic, ic->ic_bss);
1516 	}
1517 }
1518 
1519 /*
1520  * Handle a station joining an RSN network.
1521  */
1522 void
1523 ieee80211_node_join_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
1524 {
1525 	DPRINTF(("station %s associated using proto %d akm 0x%x "
1526 	    "cipher 0x%x groupcipher 0x%x\n", ether_sprintf(ni->ni_macaddr),
1527 	    ni->ni_rsnprotos, ni->ni_rsnakms, ni->ni_rsnciphers,
1528 	    ni->ni_rsngroupcipher));
1529 
1530 	ni->ni_rsn_state = RSNA_AUTHENTICATION;
1531 
1532 	ni->ni_key_count = 0;
1533 	ni->ni_port_valid = 0;
1534 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
1535 	ni->ni_replaycnt = -1;	/* XXX */
1536 	ni->ni_rsn_retries = 0;
1537 	ni->ni_rsncipher = ni->ni_rsnciphers;
1538 
1539 	ni->ni_rsn_state = RSNA_AUTHENTICATION_2;
1540 
1541 	/* generate a new authenticator nonce (ANonce) */
1542 	arc4random_buf(ni->ni_nonce, EAPOL_KEY_NONCE_LEN);
1543 
1544 	if (!ieee80211_is_8021x_akm(ni->ni_rsnakms)) {
1545 		memcpy(ni->ni_pmk, ic->ic_psk, IEEE80211_PMK_LEN);
1546 		ni->ni_flags |= IEEE80211_NODE_PMK;
1547 		(void)ieee80211_send_4way_msg1(ic, ni);
1548 	} else if (ni->ni_flags & IEEE80211_NODE_PMK) {
1549 		/* skip 802.1X auth if a cached PMK was found */
1550 		(void)ieee80211_send_4way_msg1(ic, ni);
1551 	} else {
1552 		/* no cached PMK found, needs full 802.1X auth */
1553 		ieee80211_needs_auth(ic, ni);
1554 	}
1555 }
1556 
1557 void
1558 ieee80211_count_longslotsta(void *arg, struct ieee80211_node *ni)
1559 {
1560 	int *longslotsta = arg;
1561 
1562 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
1563 		return;
1564 
1565 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME))
1566 		(*longslotsta)++;
1567 }
1568 
1569 void
1570 ieee80211_count_nonerpsta(void *arg, struct ieee80211_node *ni)
1571 {
1572 	int *nonerpsta = arg;
1573 
1574 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
1575 		return;
1576 
1577 	if (!ieee80211_iserp_sta(ni))
1578 		(*nonerpsta)++;
1579 }
1580 
1581 void
1582 ieee80211_count_pssta(void *arg, struct ieee80211_node *ni)
1583 {
1584 	int *pssta = arg;
1585 
1586 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
1587 		return;
1588 
1589  	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
1590 		(*pssta)++;
1591 }
1592 
1593 void
1594 ieee80211_count_rekeysta(void *arg, struct ieee80211_node *ni)
1595 {
1596 	int *rekeysta = arg;
1597 
1598 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
1599 		return;
1600 
1601 	if (ni->ni_flags & IEEE80211_NODE_REKEY)
1602 		(*rekeysta)++;
1603 }
1604 
1605 /*
1606  * Handle a station joining an 11g network.
1607  */
1608 void
1609 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1610 {
1611 	int longslotsta = 0, nonerpsta = 0;
1612 
1613 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
1614 		/*
1615 		 * Joining STA doesn't support short slot time.  We must
1616 		 * disable the use of short slot time for all other associated
1617 		 * STAs and give the driver a chance to reconfigure the
1618 		 * hardware.
1619 		 */
1620 		ieee80211_iterate_nodes(ic,
1621 		    ieee80211_count_longslotsta, &longslotsta);
1622 		if (longslotsta == 1) {
1623 			if (ic->ic_caps & IEEE80211_C_SHSLOT)
1624 				ieee80211_set_shortslottime(ic, 0);
1625 		}
1626 		DPRINTF(("[%s] station needs long slot time, count %d\n",
1627 		    ether_sprintf(ni->ni_macaddr), longslotsta));
1628 	}
1629 
1630 	if (!ieee80211_iserp_sta(ni)) {
1631 		/*
1632 		 * Joining STA is non-ERP.
1633 		 */
1634 		ieee80211_iterate_nodes(ic,
1635 		    ieee80211_count_nonerpsta, &nonerpsta);
1636 		DPRINTF(("[%s] station is non-ERP, %d non-ERP "
1637 		    "stations associated\n", ether_sprintf(ni->ni_macaddr),
1638 		    nonerpsta));
1639 		/* must enable the use of protection */
1640 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
1641 			DPRINTF(("enable use of protection\n"));
1642 			ic->ic_flags |= IEEE80211_F_USEPROT;
1643 		}
1644 
1645 		if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE))
1646 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1647 	} else
1648 		ni->ni_flags |= IEEE80211_NODE_ERP;
1649 }
1650 
1651 void
1652 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
1653     int resp)
1654 {
1655 	int newassoc = (ni->ni_state != IEEE80211_STA_ASSOC);
1656 
1657 	if (ni->ni_associd == 0) {
1658 		u_int16_t aid;
1659 
1660 		/*
1661 		 * It would be clever to search the bitmap
1662 		 * more efficiently, but this will do for now.
1663 		 */
1664 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1665 			if (!IEEE80211_AID_ISSET(aid,
1666 			    ic->ic_aid_bitmap))
1667 				break;
1668 		}
1669 		if (aid >= ic->ic_max_aid) {
1670 			IEEE80211_SEND_MGMT(ic, ni, resp,
1671 			    IEEE80211_REASON_ASSOC_TOOMANY);
1672 			ieee80211_node_leave(ic, ni);
1673 			return;
1674 		}
1675 		ni->ni_associd = aid | 0xc000;
1676 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1677 		if (ic->ic_curmode == IEEE80211_MODE_11G ||
1678 		    (ic->ic_curmode == IEEE80211_MODE_11N &&
1679 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
1680 			ieee80211_node_join_11g(ic, ni);
1681 	}
1682 
1683 	DPRINTF(("station %s %s associated at aid %d\n",
1684 	    ether_sprintf(ni->ni_macaddr), newassoc ? "newly" : "already",
1685 	    ni->ni_associd & ~0xc000));
1686 
1687 	ieee80211_ht_negotiate(ic, ni);
1688 	if (ic->ic_flags & IEEE80211_F_HTON)
1689 		ieee80211_node_join_ht(ic, ni);
1690 
1691 	/* give driver a chance to setup state like ni_txrate */
1692 	if (ic->ic_newassoc)
1693 		(*ic->ic_newassoc)(ic, ni, newassoc);
1694 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1695 	ieee80211_node_newstate(ni, IEEE80211_STA_ASSOC);
1696 
1697 	if (!(ic->ic_flags & IEEE80211_F_RSNON)) {
1698 		ni->ni_port_valid = 1;
1699 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
1700 	} else
1701 		ieee80211_node_join_rsn(ic, ni);
1702 
1703 #if NBRIDGE > 0
1704 	/*
1705 	 * If the parent interface is a bridgeport, learn
1706 	 * the node's address dynamically on this interface.
1707 	 */
1708 	if (ic->ic_if.if_bridgeport != NULL)
1709 		bridge_update(&ic->ic_if,
1710 		    (struct ether_addr *)ni->ni_macaddr, 0);
1711 #endif
1712 }
1713 
1714 /*
1715  * Handle an HT STA leaving an HT network.
1716  */
1717 void
1718 ieee80211_node_leave_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
1719 {
1720 	struct ieee80211_rx_ba *ba;
1721 	u_int8_t tid;
1722 	int i;
1723 
1724 	/* free all Block Ack records */
1725 	ieee80211_ba_del(ni);
1726 	for (tid = 0; tid < IEEE80211_NUM_TID; tid++) {
1727 		ba = &ni->ni_rx_ba[tid];
1728 		if (ba->ba_buf != NULL) {
1729 			for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
1730 				m_freem(ba->ba_buf[i].m);
1731 			free(ba->ba_buf, M_DEVBUF, 0);
1732 			ba->ba_buf = NULL;
1733 		}
1734 	}
1735 
1736 	ieee80211_clear_htcaps(ni);
1737 }
1738 
1739 /*
1740  * Handle a station leaving an RSN network.
1741  */
1742 void
1743 ieee80211_node_leave_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
1744 {
1745 	int rekeysta = 0;
1746 
1747 	ni->ni_rsn_state = RSNA_DISCONNECTED;
1748 
1749 	ni->ni_rsn_state = RSNA_INITIALIZE;
1750 	if (ni->ni_flags & IEEE80211_NODE_REKEY) {
1751 		ni->ni_flags &= ~IEEE80211_NODE_REKEY;
1752 		ieee80211_iterate_nodes(ic,
1753 		    ieee80211_count_rekeysta, &rekeysta);
1754 		if (rekeysta == 0)
1755 			ieee80211_setkeysdone(ic);
1756 	}
1757 	ni->ni_flags &= ~IEEE80211_NODE_PMK;
1758 	ni->ni_rsn_gstate = RSNA_IDLE;
1759 
1760 	timeout_del(&ni->ni_eapol_to);
1761 	timeout_del(&ni->ni_sa_query_to);
1762 
1763 	ni->ni_rsn_retries = 0;
1764 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
1765 	ni->ni_port_valid = 0;
1766 	(*ic->ic_delete_key)(ic, ni, &ni->ni_pairwise_key);
1767 }
1768 
1769 /*
1770  * Handle a station leaving an 11g network.
1771  */
1772 void
1773 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1774 {
1775 	int longslotsta = 0, nonerpsta = 0;
1776 
1777 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
1778 		/* leaving STA did not support short slot time */
1779 		ieee80211_iterate_nodes(ic,
1780 		    ieee80211_count_longslotsta, &longslotsta);
1781 		if (longslotsta == 1) {
1782 			/*
1783 			 * All associated STAs now support short slot time, so
1784 			 * enable this feature and give the driver a chance to
1785 			 * reconfigure the hardware. Notice that IBSS always
1786 			 * use a long slot time.
1787 			 */
1788 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1789 			    ic->ic_opmode != IEEE80211_M_IBSS)
1790 				ieee80211_set_shortslottime(ic, 1);
1791 		}
1792 		DPRINTF(("[%s] long slot time station leaves, count %d\n",
1793 		    ether_sprintf(ni->ni_macaddr), longslotsta));
1794 	}
1795 
1796 	if (!(ni->ni_flags & IEEE80211_NODE_ERP)) {
1797 		/* leaving STA was non-ERP */
1798 		ieee80211_iterate_nodes(ic,
1799 		    ieee80211_count_nonerpsta, &nonerpsta);
1800 		if (nonerpsta == 1) {
1801 			/*
1802 			 * All associated STAs are now ERP capable, disable use
1803 			 * of protection and re-enable short preamble support.
1804 			 */
1805 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
1806 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE)
1807 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1808 		}
1809 		DPRINTF(("[%s] non-ERP station leaves, count %d\n",
1810 		    ether_sprintf(ni->ni_macaddr), nonerpsta));
1811 	}
1812 }
1813 
1814 /*
1815  * Handle bookkeeping for station deauthentication/disassociation
1816  * when operating as an ap.
1817  */
1818 void
1819 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1820 {
1821 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
1822 		panic("not in ap mode, mode %u", ic->ic_opmode);
1823 
1824 	if (ni->ni_state == IEEE80211_STA_COLLECT)
1825 		return;
1826 	/*
1827 	 * If node wasn't previously associated all we need to do is
1828 	 * reclaim the reference.
1829 	 */
1830 	if (ni->ni_associd == 0) {
1831 		ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
1832 		return;
1833 	}
1834 
1835 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
1836 		ni->ni_pwrsave = IEEE80211_PS_AWAKE;
1837 
1838 	if (mq_purge(&ni->ni_savedq) > 0) {
1839 		if (ic->ic_set_tim != NULL)
1840 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
1841 	}
1842 
1843 	if (ic->ic_flags & IEEE80211_F_RSNON)
1844 		ieee80211_node_leave_rsn(ic, ni);
1845 
1846 	if (ic->ic_curmode == IEEE80211_MODE_11G ||
1847 	    (ic->ic_curmode == IEEE80211_MODE_11N &&
1848 	    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
1849 		ieee80211_node_leave_11g(ic, ni);
1850 
1851 	if (ni->ni_flags & IEEE80211_NODE_HT)
1852 		ieee80211_node_leave_ht(ic, ni);
1853 
1854 	if (ic->ic_node_leave != NULL)
1855 		(*ic->ic_node_leave)(ic, ni);
1856 
1857 	ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
1858 
1859 #if NBRIDGE > 0
1860 	/*
1861 	 * If the parent interface is a bridgeport, delete
1862 	 * any dynamically learned address for this node.
1863 	 */
1864 	if (ic->ic_if.if_bridgeport != NULL)
1865 		bridge_update(&ic->ic_if,
1866 		    (struct ether_addr *)ni->ni_macaddr, 1);
1867 #endif
1868 }
1869 
1870 static int
1871 ieee80211_do_slow_print(struct ieee80211com *ic, int *did_print)
1872 {
1873 	static const struct timeval merge_print_intvl = {
1874 		.tv_sec = 1, .tv_usec = 0
1875 	};
1876 	if ((ic->ic_if.if_flags & IFF_LINK0) == 0)
1877 		return 0;
1878 	if (!*did_print && (ic->ic_if.if_flags & IFF_DEBUG) == 0 &&
1879 	    !ratecheck(&ic->ic_last_merge_print, &merge_print_intvl))
1880 		return 0;
1881 
1882 	*did_print = 1;
1883 	return 1;
1884 }
1885 
1886 /* ieee80211_ibss_merge helps merge 802.11 ad hoc networks.  The
1887  * convention, set by the Wireless Ethernet Compatibility Alliance
1888  * (WECA), is that an 802.11 station will change its BSSID to match
1889  * the "oldest" 802.11 ad hoc network, on the same channel, that
1890  * has the station's desired SSID.  The "oldest" 802.11 network
1891  * sends beacons with the greatest TSF timestamp.
1892  *
1893  * Return ENETRESET if the BSSID changed, 0 otherwise.
1894  *
1895  * XXX Perhaps we should compensate for the time that elapses
1896  * between the MAC receiving the beacon and the host processing it
1897  * in ieee80211_ibss_merge.
1898  */
1899 int
1900 ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni,
1901     u_int64_t local_tsft)
1902 {
1903 	u_int64_t beacon_tsft;
1904 	int did_print = 0, sign;
1905 	union {
1906 		u_int64_t	word;
1907 		u_int8_t	tstamp[8];
1908 	} u;
1909 
1910 	/* ensure alignment */
1911 	(void)memcpy(&u, &ni->ni_tstamp[0], sizeof(u));
1912 	beacon_tsft = letoh64(u.word);
1913 
1914 	/* we are faster, let the other guy catch up */
1915 	if (beacon_tsft < local_tsft)
1916 		sign = -1;
1917 	else
1918 		sign = 1;
1919 
1920 	if (IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
1921 		if (!ieee80211_do_slow_print(ic, &did_print))
1922 			return 0;
1923 		printf("%s: tsft offset %s%llu\n", ic->ic_if.if_xname,
1924 		    (sign < 0) ? "-" : "",
1925 		    (sign < 0)
1926 			? (local_tsft - beacon_tsft)
1927 			: (beacon_tsft - local_tsft));
1928 		return 0;
1929 	}
1930 
1931 	if (sign < 0)
1932 		return 0;
1933 
1934 	if (ieee80211_match_bss(ic, ni) != 0)
1935 		return 0;
1936 
1937 	if (ieee80211_do_slow_print(ic, &did_print)) {
1938 		printf("%s: ieee80211_ibss_merge: bssid mismatch %s\n",
1939 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
1940 		printf("%s: my tsft %llu beacon tsft %llu\n",
1941 		    ic->ic_if.if_xname, local_tsft, beacon_tsft);
1942 		printf("%s: sync TSF with %s\n",
1943 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_macaddr));
1944 	}
1945 
1946 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
1947 
1948 	/* negotiate rates with new IBSS */
1949 	ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
1950 	    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1951 	if (ni->ni_rates.rs_nrates == 0) {
1952 		if (ieee80211_do_slow_print(ic, &did_print)) {
1953 			printf("%s: rates mismatch, BSSID %s\n",
1954 			    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
1955 		}
1956 		return 0;
1957 	}
1958 
1959 	if (ieee80211_do_slow_print(ic, &did_print)) {
1960 		printf("%s: sync BSSID %s -> ",
1961 		    ic->ic_if.if_xname, ether_sprintf(ic->ic_bss->ni_bssid));
1962 		printf("%s ", ether_sprintf(ni->ni_bssid));
1963 		printf("(from %s)\n", ether_sprintf(ni->ni_macaddr));
1964 	}
1965 
1966 	ieee80211_node_newstate(ni, IEEE80211_STA_BSS);
1967 	(*ic->ic_node_copy)(ic, ic->ic_bss, ni);
1968 
1969 	return ENETRESET;
1970 }
1971 
1972 void
1973 ieee80211_set_tim(struct ieee80211com *ic, int aid, int set)
1974 {
1975 	if (set)
1976 		setbit(ic->ic_tim_bitmap, aid & ~0xc000);
1977 	else
1978 		clrbit(ic->ic_tim_bitmap, aid & ~0xc000);
1979 }
1980 
1981 /*
1982  * This function shall be called by drivers immediately after every DTIM.
1983  * Transmit all group addressed MSDUs buffered at the AP.
1984  */
1985 void
1986 ieee80211_notify_dtim(struct ieee80211com *ic)
1987 {
1988 	/* NB: group addressed MSDUs are buffered in ic_bss */
1989 	struct ieee80211_node *ni = ic->ic_bss;
1990 	struct ifnet *ifp = &ic->ic_if;
1991 	struct ieee80211_frame *wh;
1992 	struct mbuf *m;
1993 
1994 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP);
1995 
1996 	while ((m = mq_dequeue(&ni->ni_savedq)) != NULL) {
1997 		if (!mq_empty(&ni->ni_savedq)) {
1998 			/* more queued frames, set the more data bit */
1999 			wh = mtod(m, struct ieee80211_frame *);
2000 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
2001 		}
2002 		mq_enqueue(&ic->ic_pwrsaveq, m);
2003 		if_start(ifp);
2004 	}
2005 	/* XXX assumes everything has been sent */
2006 	ic->ic_tim_mcast_pending = 0;
2007 }
2008 #endif	/* IEEE80211_STA_ONLY */
2009 
2010 /*
2011  * Compare nodes in the tree by lladdr
2012  */
2013 int
2014 ieee80211_node_cmp(const struct ieee80211_node *b1,
2015     const struct ieee80211_node *b2)
2016 {
2017 	return (memcmp(b1->ni_macaddr, b2->ni_macaddr, IEEE80211_ADDR_LEN));
2018 }
2019 
2020 /*
2021  * Generate red-black tree function logic
2022  */
2023 RBT_GENERATE(ieee80211_tree, ieee80211_node, ni_node, ieee80211_node_cmp);
2024