xref: /openbsd-src/sys/net80211/ieee80211_node.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*	$OpenBSD: ieee80211_node.c,v 1.182 2020/05/31 09:08:33 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 int ieee80211_node_checkrssi(struct ieee80211com *,
69     const struct ieee80211_node *);
70 int ieee80211_ess_is_better(struct ieee80211com *ic, struct ieee80211_node *,
71     struct ieee80211_node *);
72 void ieee80211_node_set_timeouts(struct ieee80211_node *);
73 void ieee80211_setup_node(struct ieee80211com *, struct ieee80211_node *,
74     const u_int8_t *);
75 struct ieee80211_node *ieee80211_alloc_node_helper(struct ieee80211com *);
76 void ieee80211_node_switch_bss(struct ieee80211com *, struct ieee80211_node *);
77 void ieee80211_node_addba_request(struct ieee80211_node *, int);
78 void ieee80211_node_addba_request_ac_be_to(void *);
79 void ieee80211_node_addba_request_ac_bk_to(void *);
80 void ieee80211_node_addba_request_ac_vi_to(void *);
81 void ieee80211_node_addba_request_ac_vo_to(void *);
82 void ieee80211_needs_auth(struct ieee80211com *, struct ieee80211_node *);
83 #ifndef IEEE80211_STA_ONLY
84 void ieee80211_node_join_ht(struct ieee80211com *, struct ieee80211_node *);
85 void ieee80211_node_join_rsn(struct ieee80211com *, struct ieee80211_node *);
86 void ieee80211_node_join_11g(struct ieee80211com *, struct ieee80211_node *);
87 void ieee80211_node_leave_ht(struct ieee80211com *, struct ieee80211_node *);
88 void ieee80211_node_leave_rsn(struct ieee80211com *, struct ieee80211_node *);
89 void ieee80211_node_leave_11g(struct ieee80211com *, struct ieee80211_node *);
90 void ieee80211_inact_timeout(void *);
91 void ieee80211_node_cache_timeout(void *);
92 #endif
93 void ieee80211_clean_inactive_nodes(struct ieee80211com *, int);
94 
95 #ifndef IEEE80211_STA_ONLY
96 void
97 ieee80211_inact_timeout(void *arg)
98 {
99 	struct ieee80211com *ic = arg;
100 	struct ieee80211_node *ni, *next_ni;
101 	int s;
102 
103 	s = splnet();
104 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
105 	    ni != NULL; ni = next_ni) {
106 		next_ni = RBT_NEXT(ieee80211_tree, ni);
107 		if (ni->ni_refcnt > 0)
108 			continue;
109 		if (ni->ni_inact < IEEE80211_INACT_MAX)
110 			ni->ni_inact++;
111 	}
112 	splx(s);
113 
114 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
115 }
116 
117 void
118 ieee80211_node_cache_timeout(void *arg)
119 {
120 	struct ieee80211com *ic = arg;
121 
122 	ieee80211_clean_nodes(ic, 1);
123 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
124 }
125 #endif
126 
127 /*
128  * For debug purposes
129  */
130 void
131 ieee80211_print_ess(struct ieee80211_ess *ess)
132 {
133 	ieee80211_print_essid(ess->essid, ess->esslen);
134 	if (ess->flags & IEEE80211_F_RSNON) {
135 		printf(" wpa");
136 		if (ess->rsnprotos & IEEE80211_PROTO_RSN)
137 			printf(",wpa2");
138 		if (ess->rsnprotos & IEEE80211_PROTO_WPA)
139 			printf(",wpa1");
140 
141 		if (ess->rsnakms & IEEE80211_AKM_8021X ||
142 		    ess->rsnakms & IEEE80211_AKM_SHA256_8021X)
143 			printf(",802.1x");
144 		printf(" ");
145 
146 		if (ess->rsnciphers & IEEE80211_CIPHER_USEGROUP)
147 			printf(" usegroup");
148 		if (ess->rsnciphers & IEEE80211_CIPHER_WEP40)
149 			printf(" wep40");
150 		if (ess->rsnciphers & IEEE80211_CIPHER_WEP104)
151 			printf(" wep104");
152 		if (ess->rsnciphers & IEEE80211_CIPHER_TKIP)
153 			printf(" tkip");
154 		if (ess->rsnciphers & IEEE80211_CIPHER_CCMP)
155 			printf(" ccmp");
156 	}
157 	if (ess->flags & IEEE80211_F_WEPON) {
158 		int i = ess->def_txkey;
159 
160 		printf(" wep,");
161 		if (ess->nw_keys[i].k_cipher & IEEE80211_CIPHER_WEP40)
162 			printf("wep40");
163 		if (ess->nw_keys[i].k_cipher & IEEE80211_CIPHER_WEP104)
164 			printf("wep104");
165 	}
166 	if (ess->flags == 0)
167 		printf(" clear");
168 	printf("\n");
169 }
170 
171 void
172 ieee80211_print_ess_list(struct ieee80211com *ic)
173 {
174 	struct ifnet		*ifp = &ic->ic_if;
175 	struct ieee80211_ess	*ess;
176 
177 	printf("%s: known networks\n", ifp->if_xname);
178 	TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
179 		ieee80211_print_ess(ess);
180 	}
181 }
182 
183 struct ieee80211_ess *
184 ieee80211_get_ess(struct ieee80211com *ic, const char *nwid, int len)
185 {
186 	struct ieee80211_ess	*ess;
187 
188 	TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
189 		if (len == ess->esslen &&
190 		    memcmp(ess->essid, nwid, ess->esslen) == 0)
191 			return ess;
192 	}
193 
194 	return NULL;
195 }
196 
197 void
198 ieee80211_del_ess(struct ieee80211com *ic, char *nwid, int len, int all)
199 {
200 	struct ieee80211_ess *ess, *next;
201 
202 	TAILQ_FOREACH_SAFE(ess, &ic->ic_ess, ess_next, next) {
203 		if (all == 1 || (ess->esslen == len &&
204 		    memcmp(ess->essid, nwid, len) == 0)) {
205 			TAILQ_REMOVE(&ic->ic_ess, ess, ess_next);
206 			explicit_bzero(ess, sizeof(*ess));
207 			free(ess, M_DEVBUF, sizeof(*ess));
208 			if (TAILQ_EMPTY(&ic->ic_ess))
209 				ic->ic_flags &= ~IEEE80211_F_AUTO_JOIN;
210 			if (all != 1)
211 				return;
212 		}
213 	}
214 }
215 
216 /* Keep in sync with ieee80211_ioctl.c:ieee80211_ioctl_setnwkeys() */
217 static int
218 ieee80211_ess_setnwkeys(struct ieee80211_ess *ess,
219     const struct ieee80211_nwkey *nwkey)
220 {
221 	struct ieee80211_key *k;
222 	int error, i;
223 
224 	if (nwkey->i_wepon == IEEE80211_NWKEY_OPEN) {
225 		if (!(ess->flags & IEEE80211_F_WEPON))
226 			return 0;
227 		ess->flags &= ~IEEE80211_F_WEPON;
228 		return ENETRESET;
229 	}
230 	if (nwkey->i_defkid < 1 || nwkey->i_defkid > IEEE80211_WEP_NKID)
231 		return EINVAL;
232 
233 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
234 		if (nwkey->i_key[i].i_keylen == 0 ||
235 		    nwkey->i_key[i].i_keydat == NULL)
236 			continue;	/* entry not set */
237 		if (nwkey->i_key[i].i_keylen > IEEE80211_KEYBUF_SIZE)
238 			return EINVAL;
239 
240 		/* map wep key to ieee80211_key */
241 		k = &ess->nw_keys[i];
242 		memset(k, 0, sizeof(*k));
243 		if (nwkey->i_key[i].i_keylen <= 5)
244 			k->k_cipher = IEEE80211_CIPHER_WEP40;
245 		else
246 			k->k_cipher = IEEE80211_CIPHER_WEP104;
247 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
248 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
249 		error = copyin(nwkey->i_key[i].i_keydat, k->k_key, k->k_len);
250 		if (error != 0)
251 			return error;
252 	}
253 	ess->def_txkey = nwkey->i_defkid - 1;
254 	ess->flags |= IEEE80211_F_WEPON;
255 
256 	return ENETRESET;
257 }
258 
259 
260 /* Keep in sync with ieee80211_ioctl.c:ieee80211_ioctl_setwpaparms() */
261 static int
262 ieee80211_ess_setwpaparms(struct ieee80211_ess *ess,
263     const struct ieee80211_wpaparams *wpa)
264 {
265 	if (!wpa->i_enabled) {
266 		if (!(ess->flags & IEEE80211_F_RSNON))
267 			return 0;
268 		ess->flags &= ~IEEE80211_F_RSNON;
269 		ess->rsnprotos = 0;
270 		ess->rsnakms = 0;
271 		ess->rsngroupcipher = 0;
272 		ess->rsnciphers = 0;
273 		return ENETRESET;
274 	}
275 
276 	ess->rsnprotos = 0;
277 	if (wpa->i_protos & IEEE80211_WPA_PROTO_WPA1)
278 		ess->rsnprotos |= IEEE80211_PROTO_WPA;
279 	if (wpa->i_protos & IEEE80211_WPA_PROTO_WPA2)
280 		ess->rsnprotos |= IEEE80211_PROTO_RSN;
281 	if (ess->rsnprotos == 0)	/* set to default (RSN) */
282 		ess->rsnprotos = IEEE80211_PROTO_RSN;
283 
284 	ess->rsnakms = 0;
285 	if (wpa->i_akms & IEEE80211_WPA_AKM_PSK)
286 		ess->rsnakms |= IEEE80211_AKM_PSK;
287 	if (wpa->i_akms & IEEE80211_WPA_AKM_SHA256_PSK)
288 		ess->rsnakms |= IEEE80211_AKM_SHA256_PSK;
289 	if (wpa->i_akms & IEEE80211_WPA_AKM_8021X)
290 		ess->rsnakms |= IEEE80211_AKM_8021X;
291 	if (wpa->i_akms & IEEE80211_WPA_AKM_SHA256_8021X)
292 		ess->rsnakms |= IEEE80211_AKM_SHA256_8021X;
293 	if (ess->rsnakms == 0)	/* set to default (PSK) */
294 		ess->rsnakms = IEEE80211_AKM_PSK;
295 
296 	if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_WEP40)
297 		ess->rsngroupcipher = IEEE80211_CIPHER_WEP40;
298 	else if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_TKIP)
299 		ess->rsngroupcipher = IEEE80211_CIPHER_TKIP;
300 	else if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_CCMP)
301 		ess->rsngroupcipher = IEEE80211_CIPHER_CCMP;
302 	else if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_WEP104)
303 		ess->rsngroupcipher = IEEE80211_CIPHER_WEP104;
304 	else  {	/* set to default */
305 		if (ess->rsnprotos & IEEE80211_PROTO_WPA)
306 			ess->rsngroupcipher = IEEE80211_CIPHER_TKIP;
307 		else
308 			ess->rsngroupcipher = IEEE80211_CIPHER_CCMP;
309 	}
310 
311 	ess->rsnciphers = 0;
312 	if (wpa->i_ciphers & IEEE80211_WPA_CIPHER_TKIP)
313 		ess->rsnciphers |= IEEE80211_CIPHER_TKIP;
314 	if (wpa->i_ciphers & IEEE80211_WPA_CIPHER_CCMP)
315 		ess->rsnciphers |= IEEE80211_CIPHER_CCMP;
316 	if (wpa->i_ciphers & IEEE80211_WPA_CIPHER_USEGROUP)
317 		ess->rsnciphers = IEEE80211_CIPHER_USEGROUP;
318 	if (ess->rsnciphers == 0) { /* set to default (CCMP, TKIP if WPA1) */
319 		ess->rsnciphers = IEEE80211_CIPHER_CCMP;
320 		if (ess->rsnprotos & IEEE80211_PROTO_WPA)
321 			ess->rsnciphers |= IEEE80211_CIPHER_TKIP;
322 	}
323 
324 	ess->flags |= IEEE80211_F_RSNON;
325 
326 	if (ess->rsnakms &
327 	    (IEEE80211_AKM_8021X|IEEE80211_WPA_AKM_SHA256_8021X))
328 		ess->flags |= IEEE80211_JOIN_8021X;
329 
330 	return ENETRESET;
331 }
332 
333 static void
334 ieee80211_ess_clear_wep(struct ieee80211_ess *ess)
335 {
336 	int i;
337 
338 	/* Disable WEP */
339 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
340 		explicit_bzero(&ess->nw_keys[i], sizeof(ess->nw_keys[0]));
341 	}
342 	ess->def_txkey = 0;
343 	ess->flags &= ~IEEE80211_F_WEPON;
344 }
345 
346 static void
347 ieee80211_ess_clear_wpa(struct ieee80211_ess *ess)
348 {
349 	/* Disable WPA */
350 	ess->rsnprotos = ess->rsnakms = ess->rsngroupcipher =
351 	    ess->rsnciphers = 0;
352 	explicit_bzero(ess->psk, sizeof(ess->psk));
353 	ess->flags &= ~(IEEE80211_F_PSK | IEEE80211_F_RSNON);
354 }
355 
356 int
357 ieee80211_add_ess(struct ieee80211com *ic, struct ieee80211_join *join)
358 {
359 	struct ieee80211_ess *ess;
360 	int new = 0, ness = 0;
361 
362 	/* only valid for station (aka, client) mode */
363 	if (ic->ic_opmode != IEEE80211_M_STA)
364 		return (0);
365 
366 	TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
367 		if (ess->esslen == join->i_len &&
368 		    memcmp(ess->essid, join->i_nwid, ess->esslen) == 0)
369 			break;
370 		ness++;
371 	}
372 
373 	if (ess == NULL) {
374 		/* if not found, and wpa/wep are set, then return */
375 		if ((join->i_flags & IEEE80211_JOIN_WPA) &&
376 		    (join->i_flags & IEEE80211_JOIN_NWKEY)) {
377 			return (EINVAL);
378 		}
379 		if (ness > IEEE80211_CACHE_SIZE)
380 			return (ERANGE);
381 		new = 1;
382 		ess = malloc(sizeof(*ess), M_DEVBUF, M_NOWAIT|M_ZERO);
383 		if (ess == NULL)
384 			return (ENOMEM);
385 		memcpy(ess->essid, join->i_nwid, join->i_len);
386 		ess->esslen = join->i_len;
387 	}
388 
389 	if (join->i_flags & IEEE80211_JOIN_WPA) {
390 		if (join->i_wpaparams.i_enabled) {
391 			if (!(ic->ic_caps & IEEE80211_C_RSN)) {
392 				free(ess, M_DEVBUF, sizeof(*ess));
393 				return ENODEV;
394 			}
395 			ieee80211_ess_setwpaparms(ess,
396 			    &join->i_wpaparams);
397 			if (join->i_flags & IEEE80211_JOIN_WPAPSK) {
398 				ess->flags |= IEEE80211_F_PSK;
399 				explicit_bzero(ess->psk, sizeof(ess->psk));
400 				memcpy(ess->psk, &join->i_wpapsk.i_psk,
401 				    sizeof(ess->psk));
402 			}
403 			ieee80211_ess_clear_wep(ess);
404 		} else {
405 			ieee80211_ess_clear_wpa(ess);
406 		}
407 	} else if (join->i_flags & IEEE80211_JOIN_NWKEY) {
408 		if (join->i_nwkey.i_wepon) {
409 			if (!(ic->ic_caps & IEEE80211_C_WEP)) {
410 				free(ess, M_DEVBUF, sizeof(*ess));
411 				return ENODEV;
412 			}
413 			ieee80211_ess_setnwkeys(ess, &join->i_nwkey);
414 			ieee80211_ess_clear_wpa(ess);
415 		} else {
416 			ieee80211_ess_clear_wep(ess);
417 		}
418 	}
419 
420 	if (new)
421 		TAILQ_INSERT_TAIL(&ic->ic_ess, ess, ess_next);
422 
423 	return (0);
424 }
425 
426 uint8_t
427 ieee80211_ess_adjust_rssi(struct ieee80211com *ic, struct ieee80211_node *ni)
428 {
429 	uint8_t rssi = ni->ni_rssi;
430 
431 	/*
432 	 * Slightly punish 2 GHz RSSI values since they are usually
433 	 * stronger than 5 GHz RSSI values.
434 	 */
435 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
436 		if (ic->ic_max_rssi) {
437 			uint8_t p = (5 * ic->ic_max_rssi) / 100;
438 	 		if (rssi >= p)
439 				rssi -= p; /* punish by 5% */
440 		} else  {
441 			if (rssi >= 8)
442 				rssi -= 8; /* punish by 8 dBm */
443 		}
444 	}
445 
446 	return rssi;
447 }
448 
449 int
450 ieee80211_ess_calculate_score(struct ieee80211com *ic,
451     struct ieee80211_node *ni)
452 {
453 	int score = 0;
454 	uint8_t	min_5ghz_rssi;
455 
456 	if (ic->ic_max_rssi)
457 		min_5ghz_rssi = IEEE80211_RSSI_THRES_RATIO_5GHZ;
458 	else
459 		min_5ghz_rssi = (uint8_t)IEEE80211_RSSI_THRES_5GHZ;
460 
461 	/* not using join any */
462 	if (ieee80211_get_ess(ic, ni->ni_essid, ni->ni_esslen))
463 		score += 32;
464 
465 	/* Calculate the crypto score */
466 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
467 		score += 16;
468 	if (ni->ni_rsnprotos & IEEE80211_PROTO_WPA)
469 		score += 8;
470 	if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
471 		score += 4;
472 
473 	/* 5GHz with a good signal */
474 	if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) &&
475 	    ni->ni_rssi > min_5ghz_rssi)
476 		score += 2;
477 
478 	/* Boost this AP if it had no auth/assoc failures in the past. */
479 	if (ni->ni_fails == 0)
480 		score += 21;
481 
482 	return score;
483 }
484 
485 /*
486  * Given two APs, determine the "better" one of the two.
487  * We compute a score based on the following attributes:
488  *
489  *  crypto: wpa2 > wpa1 > wep > open
490  *  band: 5 GHz > 2 GHz provided 5 GHz rssi is above threshold
491  *  rssi: rssi1 > rssi2 as a numeric comparison with a slight
492  *         disadvantage for 2 GHz APs
493  *
494  * Crypto carries most weight, followed by band, followed by rssi.
495  */
496 int
497 ieee80211_ess_is_better(struct ieee80211com *ic,
498     struct ieee80211_node *nicur, struct ieee80211_node *nican)
499 {
500 	struct ifnet		*ifp = &ic->ic_if;
501 	int			 score_cur = 0, score_can = 0;
502 	int			 cur_rssi, can_rssi;
503 
504 	score_cur = ieee80211_ess_calculate_score(ic, nicur);
505 	score_can = ieee80211_ess_calculate_score(ic, nican);
506 
507 	cur_rssi = ieee80211_ess_adjust_rssi(ic, nicur);
508 	can_rssi = ieee80211_ess_adjust_rssi(ic, nican);
509 
510 	if (can_rssi > cur_rssi)
511 		score_can++;
512 
513 	if ((ifp->if_flags & IFF_DEBUG) && (score_can <= score_cur)) {
514 		printf("%s: AP %s ", ifp->if_xname,
515 		    ether_sprintf(nican->ni_bssid));
516 		ieee80211_print_essid(nican->ni_essid, nican->ni_esslen);
517 		printf(" score %d\n", score_can);
518 	}
519 
520 	return score_can > score_cur;
521 }
522 
523 /* Determine whether a candidate AP belongs to a given ESS. */
524 int
525 ieee80211_match_ess(struct ieee80211_ess *ess, struct ieee80211_node *ni)
526 {
527 	if (ess->esslen != 0 &&
528 	    (ess->esslen != ni->ni_esslen ||
529 	    memcmp(ess->essid, ni->ni_essid, ess->esslen) != 0)) {
530 		ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_ESSID;
531 		return 0;
532 	}
533 
534 	if (ess->flags & (IEEE80211_F_PSK | IEEE80211_F_RSNON)) {
535 		/* Ensure same WPA version. */
536 		if ((ni->ni_rsnprotos & IEEE80211_PROTO_RSN) &&
537 		    (ess->rsnprotos & IEEE80211_PROTO_RSN) == 0) {
538 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
539 			return 0;
540 		}
541 		if ((ni->ni_rsnprotos & IEEE80211_PROTO_WPA) &&
542 		    (ess->rsnprotos & IEEE80211_PROTO_WPA) == 0) {
543 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
544 			return 0;
545 		}
546 	} else if (ess->flags & IEEE80211_F_WEPON) {
547 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0) {
548 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
549 			return 0;
550 		}
551 	} else {
552 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) != 0) {
553 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
554 			return 0;
555 		}
556 	}
557 
558 	if (ess->esslen == 0 &&
559 	    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) != 0) {
560 		ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
561 		return 0;
562 	}
563 
564 	return 1;
565 }
566 
567 void
568 ieee80211_switch_ess(struct ieee80211com *ic)
569 {
570 	struct ifnet		*ifp = &ic->ic_if;
571 	struct ieee80211_ess	*ess, *seless = NULL;
572 	struct ieee80211_node	*ni, *selni = NULL;
573 
574 	if (!ISSET(ifp->if_flags, IFF_RUNNING))
575 		return;
576 
577 	/* Find the best AP matching an entry on our ESS join list. */
578 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree) {
579 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
580 		    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
581 			continue;
582 
583 		TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
584 			if (ieee80211_match_ess(ess, ni))
585 				break;
586 		}
587 		if (ess == NULL)
588 			continue;
589 
590 		/*
591 		 * Operate only on ic_des_essid if auto-join is disabled.
592 		 * We might have a password stored for this network.
593 		 */
594 		if (!ISSET(ic->ic_flags, IEEE80211_F_AUTO_JOIN)) {
595 			if (ic->ic_des_esslen == ni->ni_esslen &&
596 			    memcmp(ic->ic_des_essid, ni->ni_essid,
597 			    ni->ni_esslen) == 0) {
598 				ieee80211_set_ess(ic, ess, ni);
599 				return;
600 			}
601 			continue;
602 		}
603 
604 		if (selni == NULL) {
605 			seless = ess;
606 			selni = ni;
607 			continue;
608 		}
609 
610 		if (ieee80211_ess_is_better(ic, selni, ni)) {
611 			seless = ess;
612 			selni = ni;
613 		}
614 	}
615 
616 	if (selni && seless && !(selni->ni_esslen == ic->ic_des_esslen &&
617 	    (memcmp(ic->ic_des_essid, selni->ni_essid,
618 	     IEEE80211_NWID_LEN) == 0))) {
619 		if (ifp->if_flags & IFF_DEBUG) {
620 			printf("%s: best AP %s ", ifp->if_xname,
621 			    ether_sprintf(selni->ni_bssid));
622 			ieee80211_print_essid(selni->ni_essid,
623 			    selni->ni_esslen);
624 			printf(" score %d\n",
625 			    ieee80211_ess_calculate_score(ic, selni));
626 			printf("%s: switching to network ", ifp->if_xname);
627 			ieee80211_print_essid(selni->ni_essid,
628 			    selni->ni_esslen);
629 			if (seless->esslen == 0)
630 				printf(" via join any");
631 			printf("\n");
632 
633 		}
634 		ieee80211_set_ess(ic, seless, selni);
635 	}
636 }
637 
638 void
639 ieee80211_set_ess(struct ieee80211com *ic, struct ieee80211_ess *ess,
640     struct ieee80211_node *ni)
641 {
642 	memset(ic->ic_des_essid, 0, IEEE80211_NWID_LEN);
643 	ic->ic_des_esslen = ni->ni_esslen;
644 	memcpy(ic->ic_des_essid, ni->ni_essid, ic->ic_des_esslen);
645 
646 	ieee80211_disable_wep(ic);
647 	ieee80211_disable_rsn(ic);
648 
649 	if (ess->flags & IEEE80211_F_RSNON) {
650 		explicit_bzero(ic->ic_psk, sizeof(ic->ic_psk));
651 		memcpy(ic->ic_psk, ess->psk, sizeof(ic->ic_psk));
652 
653 		ic->ic_rsnprotos = ess->rsnprotos;
654 		ic->ic_rsnakms = ess->rsnakms;
655 		ic->ic_rsngroupcipher = ess->rsngroupcipher;
656 		ic->ic_rsnciphers = ess->rsnciphers;
657 		ic->ic_flags |= IEEE80211_F_RSNON;
658 		if (ess->flags & IEEE80211_F_PSK)
659 			ic->ic_flags |= IEEE80211_F_PSK;
660 	} else if (ess->flags & IEEE80211_F_WEPON) {
661 		struct ieee80211_key	*k;
662 		int			 i;
663 
664 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
665 			k = &ic->ic_nw_keys[i];
666 			if (k->k_cipher != IEEE80211_CIPHER_NONE)
667 				(*ic->ic_delete_key)(ic, NULL, k);
668 			memcpy(&ic->ic_nw_keys[i], &ess->nw_keys[i],
669 			    sizeof(struct ieee80211_key));
670 			(*ic->ic_set_key)(ic, NULL, k);
671 		}
672 		ic->ic_def_txkey = ess->def_txkey;
673 		ic->ic_flags |= IEEE80211_F_WEPON;
674 	}
675 }
676 
677 void
678 ieee80211_deselect_ess(struct ieee80211com *ic)
679 {
680 	memset(ic->ic_des_essid, 0, IEEE80211_NWID_LEN);
681 	ic->ic_des_esslen = 0;
682 	ieee80211_disable_wep(ic);
683 	ieee80211_disable_rsn(ic);
684 }
685 
686 void
687 ieee80211_node_attach(struct ifnet *ifp)
688 {
689 	struct ieee80211com *ic = (void *)ifp;
690 #ifndef IEEE80211_STA_ONLY
691 	int size;
692 #endif
693 
694 	RBT_INIT(ieee80211_tree, &ic->ic_tree);
695 	ic->ic_node_alloc = ieee80211_node_alloc;
696 	ic->ic_node_free = ieee80211_node_free;
697 	ic->ic_node_copy = ieee80211_node_copy;
698 	ic->ic_node_getrssi = ieee80211_node_getrssi;
699 	ic->ic_node_checkrssi = ieee80211_node_checkrssi;
700 	ic->ic_scangen = 1;
701 	ic->ic_max_nnodes = ieee80211_cache_size;
702 
703 	if (ic->ic_max_aid == 0)
704 		ic->ic_max_aid = IEEE80211_AID_DEF;
705 	else if (ic->ic_max_aid > IEEE80211_AID_MAX)
706 		ic->ic_max_aid = IEEE80211_AID_MAX;
707 #ifndef IEEE80211_STA_ONLY
708 	size = howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t);
709 	ic->ic_aid_bitmap = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
710 	if (ic->ic_aid_bitmap == NULL) {
711 		/* XXX no way to recover */
712 		printf("%s: no memory for AID bitmap!\n", __func__);
713 		ic->ic_max_aid = 0;
714 	}
715 	if (ic->ic_caps & (IEEE80211_C_HOSTAP | IEEE80211_C_IBSS)) {
716 		ic->ic_tim_len = howmany(ic->ic_max_aid, 8);
717 		ic->ic_tim_bitmap = malloc(ic->ic_tim_len, M_DEVBUF,
718 		    M_NOWAIT | M_ZERO);
719 		if (ic->ic_tim_bitmap == NULL) {
720 			printf("%s: no memory for TIM bitmap!\n", __func__);
721 			ic->ic_tim_len = 0;
722 		} else
723 			ic->ic_set_tim = ieee80211_set_tim;
724 		timeout_set(&ic->ic_rsn_timeout,
725 		    ieee80211_gtk_rekey_timeout, ic);
726 		timeout_set(&ic->ic_inact_timeout,
727 		    ieee80211_inact_timeout, ic);
728 		timeout_set(&ic->ic_node_cache_timeout,
729 		    ieee80211_node_cache_timeout, ic);
730 	}
731 #endif
732 	TAILQ_INIT(&ic->ic_ess);
733 }
734 
735 struct ieee80211_node *
736 ieee80211_alloc_node_helper(struct ieee80211com *ic)
737 {
738 	struct ieee80211_node *ni;
739 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
740 		ieee80211_clean_nodes(ic, 0);
741 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
742 		return NULL;
743 	ni = (*ic->ic_node_alloc)(ic);
744 	return ni;
745 }
746 
747 void
748 ieee80211_node_lateattach(struct ifnet *ifp)
749 {
750 	struct ieee80211com *ic = (void *)ifp;
751 	struct ieee80211_node *ni;
752 
753 	ni = ieee80211_alloc_node_helper(ic);
754 	if (ni == NULL)
755 		panic("unable to setup inital BSS node");
756 	ni->ni_chan = IEEE80211_CHAN_ANYC;
757 	ic->ic_bss = ieee80211_ref_node(ni);
758 	ic->ic_txpower = IEEE80211_TXPOWER_MAX;
759 #ifndef IEEE80211_STA_ONLY
760 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
761 #endif
762 }
763 
764 void
765 ieee80211_node_detach(struct ifnet *ifp)
766 {
767 	struct ieee80211com *ic = (void *)ifp;
768 
769 	if (ic->ic_bss != NULL) {
770 		(*ic->ic_node_free)(ic, ic->ic_bss);
771 		ic->ic_bss = NULL;
772 	}
773 	ieee80211_del_ess(ic, NULL, 0, 1);
774 	ieee80211_free_allnodes(ic, 1);
775 #ifndef IEEE80211_STA_ONLY
776 	free(ic->ic_aid_bitmap, M_DEVBUF,
777 	    howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t));
778 	free(ic->ic_tim_bitmap, M_DEVBUF, ic->ic_tim_len);
779 	timeout_del(&ic->ic_inact_timeout);
780 	timeout_del(&ic->ic_node_cache_timeout);
781 	timeout_del(&ic->ic_tkip_micfail_timeout);
782 #endif
783 	timeout_del(&ic->ic_rsn_timeout);
784 }
785 
786 /*
787  * AP scanning support.
788  */
789 
790 /*
791  * Initialize the active channel set based on the set
792  * of available channels and the current PHY mode.
793  */
794 void
795 ieee80211_reset_scan(struct ifnet *ifp)
796 {
797 	struct ieee80211com *ic = (void *)ifp;
798 
799 	memcpy(ic->ic_chan_scan, ic->ic_chan_active,
800 		sizeof(ic->ic_chan_active));
801 	/* NB: hack, setup so next_scan starts with the first channel */
802 	if (ic->ic_bss != NULL && ic->ic_bss->ni_chan == IEEE80211_CHAN_ANYC)
803 		ic->ic_bss->ni_chan = &ic->ic_channels[IEEE80211_CHAN_MAX];
804 }
805 
806 /*
807  * Increase a node's inactivity counter.
808  * This counter get reset to zero if a frame is received.
809  * This function is intended for station mode only.
810  * See ieee80211_node_cache_timeout() for hostap mode.
811  */
812 void
813 ieee80211_node_raise_inact(void *arg, struct ieee80211_node *ni)
814 {
815 	if (ni->ni_refcnt == 0 && ni->ni_inact < IEEE80211_INACT_SCAN)
816 		ni->ni_inact++;
817 }
818 
819 /*
820  * Begin an active scan.
821  */
822 void
823 ieee80211_begin_scan(struct ifnet *ifp)
824 {
825 	struct ieee80211com *ic = (void *)ifp;
826 
827 	/*
828 	 * In all but hostap mode scanning starts off in
829 	 * an active mode before switching to passive.
830 	 */
831 #ifndef IEEE80211_STA_ONLY
832 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
833 #endif
834 	{
835 		ic->ic_flags |= IEEE80211_F_ASCAN;
836 		ic->ic_stats.is_scan_active++;
837 	}
838 #ifndef IEEE80211_STA_ONLY
839 	else
840 		ic->ic_stats.is_scan_passive++;
841 #endif
842 	if (ifp->if_flags & IFF_DEBUG)
843 		printf("%s: begin %s scan\n", ifp->if_xname,
844 			(ic->ic_flags & IEEE80211_F_ASCAN) ?
845 				"active" : "passive");
846 
847 
848 	if (ic->ic_opmode == IEEE80211_M_STA) {
849 		ieee80211_node_cleanup(ic, ic->ic_bss);
850 		ieee80211_iterate_nodes(ic, ieee80211_node_raise_inact, NULL);
851 	}
852 
853 	/*
854 	 * Reset the current mode. Setting the current mode will also
855 	 * reset scan state.
856 	 */
857 	if (IFM_MODE(ic->ic_media.ifm_cur->ifm_media) == IFM_AUTO)
858 		ic->ic_curmode = IEEE80211_MODE_AUTO;
859 	ieee80211_setmode(ic, ic->ic_curmode);
860 
861 	ic->ic_scan_count = 0;
862 
863 	/* Scan the next channel. */
864 	ieee80211_next_scan(ifp);
865 }
866 
867 /*
868  * Switch to the next channel marked for scanning.
869  */
870 void
871 ieee80211_next_scan(struct ifnet *ifp)
872 {
873 	struct ieee80211com *ic = (void *)ifp;
874 	struct ieee80211_channel *chan;
875 
876 	chan = ic->ic_bss->ni_chan;
877 	for (;;) {
878 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
879 			chan = &ic->ic_channels[0];
880 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
881 			/*
882 			 * Ignore channels marked passive-only
883 			 * during an active scan.
884 			 */
885 			if ((ic->ic_flags & IEEE80211_F_ASCAN) == 0 ||
886 			    (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
887 				break;
888 		}
889 		if (chan == ic->ic_bss->ni_chan) {
890 			ieee80211_end_scan(ifp);
891 			return;
892 		}
893 	}
894 	clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
895 	DPRINTF(("chan %d->%d\n",
896 	    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
897 	    ieee80211_chan2ieee(ic, chan)));
898 	ic->ic_bss->ni_chan = chan;
899 	ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
900 }
901 
902 #ifndef IEEE80211_STA_ONLY
903 void
904 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
905 {
906 	struct ieee80211_node *ni;
907 	struct ifnet *ifp = &ic->ic_if;
908 
909 	ni = ic->ic_bss;
910 	if (ifp->if_flags & IFF_DEBUG)
911 		printf("%s: creating ibss\n", ifp->if_xname);
912 	ic->ic_flags |= IEEE80211_F_SIBSS;
913 	ni->ni_chan = chan;
914 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, ni->ni_chan)];
915 	ni->ni_txrate = 0;
916 	IEEE80211_ADDR_COPY(ni->ni_macaddr, ic->ic_myaddr);
917 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
918 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
919 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) != 0)
920 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
921 		else
922 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
923 	}
924 	ni->ni_esslen = ic->ic_des_esslen;
925 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
926 	ni->ni_rssi = 0;
927 	ni->ni_rstamp = 0;
928 	memset(ni->ni_tstamp, 0, sizeof(ni->ni_tstamp));
929 	ni->ni_intval = ic->ic_lintval;
930 	ni->ni_capinfo = IEEE80211_CAPINFO_IBSS;
931 	if (ic->ic_flags & IEEE80211_F_WEPON)
932 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
933 	if (ic->ic_flags & IEEE80211_F_HTON) {
934 		const struct ieee80211_edca_ac_params *ac_qap;
935 		struct ieee80211_edca_ac_params *ac;
936 		int aci;
937 
938 		/*
939 		 * Configure HT protection. This will be updated later
940 		 * based on the number of non-HT nodes in the node cache.
941 		 */
942 		ic->ic_protmode = IEEE80211_PROT_NONE;
943 		ni->ni_htop1 = IEEE80211_HTPROT_NONE;
944 		/* Disallow Greenfield mode. None of our drivers support it. */
945 		ni->ni_htop1 |= IEEE80211_HTOP1_NONGF_STA;
946 		if (ic->ic_update_htprot)
947 			ic->ic_update_htprot(ic, ni);
948 
949 		/* Configure QoS EDCA parameters. */
950 		for (aci = 0; aci < EDCA_NUM_AC; aci++) {
951 			ac = &ic->ic_edca_ac[aci];
952 			ac_qap = &ieee80211_qap_edca_table[ic->ic_curmode][aci];
953 			ac->ac_acm       = ac_qap->ac_acm;
954 			ac->ac_aifsn     = ac_qap->ac_aifsn;
955 			ac->ac_ecwmin    = ac_qap->ac_ecwmin;
956 			ac->ac_ecwmax    = ac_qap->ac_ecwmax;
957 			ac->ac_txoplimit = ac_qap->ac_txoplimit;
958 		}
959 		if (ic->ic_updateedca)
960 			(*ic->ic_updateedca)(ic);
961 	}
962 	if (ic->ic_flags & IEEE80211_F_RSNON) {
963 		struct ieee80211_key *k;
964 
965 		/* initialize 256-bit global key counter to a random value */
966 		arc4random_buf(ic->ic_globalcnt, EAPOL_KEY_NONCE_LEN);
967 
968 		ni->ni_rsnprotos = ic->ic_rsnprotos;
969 		ni->ni_rsnakms = ic->ic_rsnakms;
970 		ni->ni_rsnciphers = ic->ic_rsnciphers;
971 		ni->ni_rsngroupcipher = ic->ic_rsngroupcipher;
972 		ni->ni_rsngroupmgmtcipher = ic->ic_rsngroupmgmtcipher;
973 		ni->ni_rsncaps = 0;
974 		if (ic->ic_caps & IEEE80211_C_MFP) {
975 			ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPC;
976 			if (ic->ic_flags & IEEE80211_F_MFPR)
977 				ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPR;
978 		}
979 
980 		ic->ic_def_txkey = 1;
981 		ic->ic_flags &= ~IEEE80211_F_COUNTERM;
982 		k = &ic->ic_nw_keys[ic->ic_def_txkey];
983 		memset(k, 0, sizeof(*k));
984 		k->k_id = ic->ic_def_txkey;
985 		k->k_cipher = ni->ni_rsngroupcipher;
986 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
987 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
988 		arc4random_buf(k->k_key, k->k_len);
989 		(*ic->ic_set_key)(ic, ni, k);	/* XXX */
990 
991 		if (ic->ic_caps & IEEE80211_C_MFP) {
992 			ic->ic_igtk_kid = 4;
993 			k = &ic->ic_nw_keys[ic->ic_igtk_kid];
994 			memset(k, 0, sizeof(*k));
995 			k->k_id = ic->ic_igtk_kid;
996 			k->k_cipher = ni->ni_rsngroupmgmtcipher;
997 			k->k_flags = IEEE80211_KEY_IGTK | IEEE80211_KEY_TX;
998 			k->k_len = 16;
999 			arc4random_buf(k->k_key, k->k_len);
1000 			(*ic->ic_set_key)(ic, ni, k);	/* XXX */
1001 		}
1002 		/*
1003 		 * In HostAP mode, multicast traffic is sent using ic_bss
1004 		 * as the Tx node, so mark our node as valid so we can send
1005 		 * multicast frames using the group key we've just configured.
1006 		 */
1007 		ni->ni_port_valid = 1;
1008 		ni->ni_flags |= IEEE80211_NODE_TXPROT;
1009 
1010 		/* schedule a GTK/IGTK rekeying after 3600s */
1011 		timeout_add_sec(&ic->ic_rsn_timeout, 3600);
1012 	}
1013 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
1014 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
1015 	ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1016 }
1017 #endif	/* IEEE80211_STA_ONLY */
1018 
1019 int
1020 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni,
1021     int bgscan)
1022 {
1023 	u_int8_t rate;
1024 	int fail;
1025 
1026 	fail = 0;
1027 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
1028 		fail |= IEEE80211_NODE_ASSOCFAIL_CHAN;
1029 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
1030 	    ni->ni_chan != ic->ic_des_chan)
1031 		fail |= IEEE80211_NODE_ASSOCFAIL_CHAN;
1032 #ifndef IEEE80211_STA_ONLY
1033 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1034 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
1035 			fail |= IEEE80211_NODE_ASSOCFAIL_IBSS;
1036 	} else
1037 #endif
1038 	{
1039 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
1040 			fail |= IEEE80211_NODE_ASSOCFAIL_IBSS;
1041 	}
1042 	if (ic->ic_flags & (IEEE80211_F_WEPON | IEEE80211_F_RSNON)) {
1043 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
1044 			fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
1045 	} else {
1046 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
1047 			fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
1048 	}
1049 
1050 	rate = ieee80211_fix_rate(ic, ni, IEEE80211_F_DONEGO);
1051 	if (rate & IEEE80211_RATE_BASIC)
1052 		fail |= IEEE80211_NODE_ASSOCFAIL_BASIC_RATE;
1053 	if (ic->ic_des_esslen == 0)
1054 		fail |= IEEE80211_NODE_ASSOCFAIL_ESSID;
1055 	if (ic->ic_des_esslen != 0 &&
1056 	    (ni->ni_esslen != ic->ic_des_esslen ||
1057 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
1058 		fail |= IEEE80211_NODE_ASSOCFAIL_ESSID;
1059 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
1060 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
1061 		fail |= IEEE80211_NODE_ASSOCFAIL_BSSID;
1062 
1063 	if (ic->ic_flags & IEEE80211_F_RSNON) {
1064 		/*
1065 		 * If at least one RSN IE field from the AP's RSN IE fails
1066 		 * to overlap with any value the STA supports, the STA shall
1067 		 * decline to associate with that AP.
1068 		 */
1069 		if ((ni->ni_rsnprotos & ic->ic_rsnprotos) == 0)
1070 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1071 		if ((ni->ni_rsnakms & ic->ic_rsnakms) == 0)
1072 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1073 		if ((ni->ni_rsnakms & ic->ic_rsnakms &
1074 		     ~(IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK)) == 0) {
1075 			/* AP only supports PSK AKMPs */
1076 			if (!(ic->ic_flags & IEEE80211_F_PSK))
1077 				fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1078 		}
1079 		if (ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP40 &&
1080 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_TKIP &&
1081 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_CCMP &&
1082 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP104)
1083 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1084 		if ((ni->ni_rsnciphers & ic->ic_rsnciphers) == 0)
1085 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1086 
1087 		/* we only support BIP as the IGTK cipher */
1088 		if ((ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC) &&
1089 		    ni->ni_rsngroupmgmtcipher != IEEE80211_CIPHER_BIP)
1090 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1091 
1092 		/* we do not support MFP but AP requires it */
1093 		if (!(ic->ic_caps & IEEE80211_C_MFP) &&
1094 		    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPR))
1095 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1096 
1097 		/* we require MFP but AP does not support it */
1098 		if ((ic->ic_caps & IEEE80211_C_MFP) &&
1099 		    (ic->ic_flags & IEEE80211_F_MFPR) &&
1100 		    !(ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
1101 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1102 	}
1103 
1104 	if (ic->ic_if.if_flags & IFF_DEBUG) {
1105 		printf("%s: %c %s%c", ic->ic_if.if_xname, fail ? '-' : '+',
1106 		    ether_sprintf(ni->ni_bssid),
1107 		    fail & IEEE80211_NODE_ASSOCFAIL_BSSID ? '!' : ' ');
1108 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
1109 			fail & IEEE80211_NODE_ASSOCFAIL_CHAN ? '!' : ' ');
1110 		printf(" %+4d", ni->ni_rssi);
1111 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1112 		    fail & IEEE80211_NODE_ASSOCFAIL_BASIC_RATE ? '!' : ' ');
1113 		printf(" %4s%c",
1114 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1115 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
1116 		    "????",
1117 		    fail & IEEE80211_NODE_ASSOCFAIL_IBSS ? '!' : ' ');
1118 		printf(" %7s%c ",
1119 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1120 		    "privacy" : "no",
1121 		    fail & IEEE80211_NODE_ASSOCFAIL_PRIVACY ? '!' : ' ');
1122 		printf(" %3s%c ",
1123 		    (ic->ic_flags & IEEE80211_F_RSNON) ?
1124 		    "rsn" : "no",
1125 		    fail & IEEE80211_NODE_ASSOCFAIL_WPA_PROTO ? '!' : ' ');
1126 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
1127 		printf("%s\n",
1128 		    fail & IEEE80211_NODE_ASSOCFAIL_ESSID ? "!" : "");
1129 	}
1130 
1131 	/* We don't care about unrelated networks during background scans. */
1132 	if (bgscan) {
1133 		if ((fail & IEEE80211_NODE_ASSOCFAIL_ESSID) == 0)
1134 			ni->ni_assoc_fail = fail;
1135 	} else
1136 		ni->ni_assoc_fail = fail;
1137 	if ((fail & IEEE80211_NODE_ASSOCFAIL_ESSID) == 0)
1138 		ic->ic_bss->ni_assoc_fail = ni->ni_assoc_fail;
1139 
1140 	return fail;
1141 }
1142 
1143 struct ieee80211_node_switch_bss_arg {
1144 	u_int8_t cur_macaddr[IEEE80211_ADDR_LEN];
1145 	u_int8_t sel_macaddr[IEEE80211_ADDR_LEN];
1146 };
1147 
1148 /* Implements ni->ni_unref_cb(). */
1149 void
1150 ieee80211_node_switch_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
1151 {
1152 	struct ifnet *ifp = &ic->ic_if;
1153 	struct ieee80211_node_switch_bss_arg *sba = ni->ni_unref_arg;
1154 	struct ieee80211_node *curbs, *selbs;
1155 
1156 	splassert(IPL_NET);
1157 
1158 	if ((ic->ic_flags & IEEE80211_F_BGSCAN) == 0) {
1159 		free(sba, M_DEVBUF, sizeof(*sba));
1160 		return;
1161 	}
1162 
1163 	ic->ic_xflags &= ~IEEE80211_F_TX_MGMT_ONLY;
1164 
1165 	selbs = ieee80211_find_node(ic, sba->sel_macaddr);
1166 	if (selbs == NULL) {
1167 		free(sba, M_DEVBUF, sizeof(*sba));
1168 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1169 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1170 		return;
1171 	}
1172 
1173 	curbs = ieee80211_find_node(ic, sba->cur_macaddr);
1174 	if (curbs == NULL) {
1175 		free(sba, M_DEVBUF, sizeof(*sba));
1176 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1177 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1178 		return;
1179 	}
1180 
1181 	if (ifp->if_flags & IFF_DEBUG) {
1182 		printf("%s: roaming from %s chan %d ",
1183 		    ifp->if_xname, ether_sprintf(curbs->ni_macaddr),
1184 		    ieee80211_chan2ieee(ic, curbs->ni_chan));
1185 		printf("to %s chan %d\n", ether_sprintf(selbs->ni_macaddr),
1186 		    ieee80211_chan2ieee(ic, selbs->ni_chan));
1187 	}
1188 	ieee80211_node_newstate(curbs, IEEE80211_STA_CACHE);
1189 	ieee80211_node_join_bss(ic, selbs); /* frees arg and ic->ic_bss */
1190 }
1191 
1192 void
1193 ieee80211_node_join_bss(struct ieee80211com *ic, struct ieee80211_node *selbs)
1194 {
1195 	enum ieee80211_phymode mode;
1196 	struct ieee80211_node *ni;
1197 	uint32_t assoc_fail = 0;
1198 
1199 	/* Reinitialize media mode and channels if needed. */
1200 	mode = ieee80211_chan2mode(ic, selbs->ni_chan);
1201 	if (mode != ic->ic_curmode)
1202 		ieee80211_setmode(ic, mode);
1203 
1204 	/* Keep recorded association failures for this BSS/ESS intact. */
1205 	if (IEEE80211_ADDR_EQ(ic->ic_bss->ni_macaddr, selbs->ni_macaddr) ||
1206 	    (ic->ic_des_esslen > 0 && ic->ic_des_esslen == selbs->ni_esslen &&
1207 	    memcmp(ic->ic_des_essid, selbs->ni_essid, selbs->ni_esslen) == 0))
1208 		assoc_fail = ic->ic_bss->ni_assoc_fail;
1209 
1210 	(*ic->ic_node_copy)(ic, ic->ic_bss, selbs);
1211 	ni = ic->ic_bss;
1212 	ni->ni_assoc_fail |= assoc_fail;
1213 
1214 	ic->ic_curmode = ieee80211_chan2mode(ic, ni->ni_chan);
1215 
1216 	/* Make sure we send valid rates in an association request. */
1217 	if (ic->ic_opmode == IEEE80211_M_STA)
1218 		ieee80211_fix_rate(ic, ni,
1219 		    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1220 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1221 
1222 	if (ic->ic_flags & IEEE80211_F_RSNON)
1223 		ieee80211_choose_rsnparams(ic);
1224 	else if (ic->ic_flags & IEEE80211_F_WEPON)
1225 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
1226 
1227 	ieee80211_node_newstate(selbs, IEEE80211_STA_BSS);
1228 #ifndef IEEE80211_STA_ONLY
1229 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1230 		ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
1231 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1232 		if (ni->ni_rates.rs_nrates == 0) {
1233 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1234 			return;
1235 		}
1236 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1237 	} else
1238 #endif
1239 	{
1240 		int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
1241 		    ic->ic_opmode == IEEE80211_M_STA &&
1242 		    ic->ic_state == IEEE80211_S_RUN);
1243 		int auth_next = (ic->ic_opmode == IEEE80211_M_STA &&
1244 		    ic->ic_state == IEEE80211_S_AUTH);
1245 		int mgt = -1;
1246 
1247 		timeout_del(&ic->ic_bgscan_timeout);
1248 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1249 
1250 		/*
1251 		 * After a background scan, we have now switched APs.
1252 		 * Pretend we were just de-authed, which makes
1253 		 * ieee80211_new_state() try to re-auth and thus send
1254 		 * an AUTH frame to our newly selected AP.
1255 		 */
1256 		if (bgscan)
1257 			mgt = IEEE80211_FC0_SUBTYPE_DEAUTH;
1258 		/*
1259 		 * If we are trying another AP after the previous one
1260 		 * failed (state transition AUTH->AUTH), ensure that
1261 		 * ieee80211_new_state() tries to send another auth frame.
1262 		 */
1263 		else if (auth_next)
1264 			mgt = IEEE80211_FC0_SUBTYPE_AUTH;
1265 
1266 		ieee80211_new_state(ic, IEEE80211_S_AUTH, mgt);
1267 	}
1268 }
1269 
1270 struct ieee80211_node *
1271 ieee80211_node_choose_bss(struct ieee80211com *ic, int bgscan,
1272     struct ieee80211_node **curbs)
1273 {
1274 	struct ieee80211_node *ni, *nextbs, *selbs = NULL,
1275 	    *selbs2 = NULL, *selbs5 = NULL;
1276 	uint8_t min_5ghz_rssi;
1277 
1278 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1279 
1280 	for (; ni != NULL; ni = nextbs) {
1281 		nextbs = RBT_NEXT(ieee80211_tree, ni);
1282 		if (ni->ni_fails) {
1283 			/*
1284 			 * The configuration of the access points may change
1285 			 * during my scan.  So delete the entry for the AP
1286 			 * and retry to associate if there is another beacon.
1287 			 */
1288 			if (ni->ni_fails++ > 2)
1289 				ieee80211_free_node(ic, ni);
1290 			continue;
1291 		}
1292 
1293 		if (curbs && ieee80211_node_cmp(ic->ic_bss, ni) == 0)
1294 			*curbs = ni;
1295 
1296 		if (ieee80211_match_bss(ic, ni, bgscan) != 0)
1297 			continue;
1298 
1299 		if (ic->ic_caps & IEEE80211_C_SCANALLBAND) {
1300 			if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan) &&
1301 			    (selbs2 == NULL || ni->ni_rssi > selbs2->ni_rssi))
1302 				selbs2 = ni;
1303 			else if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) &&
1304 			    (selbs5 == NULL || ni->ni_rssi > selbs5->ni_rssi))
1305 				selbs5 = ni;
1306 		} else if (selbs == NULL || ni->ni_rssi > selbs->ni_rssi)
1307 			selbs = ni;
1308 	}
1309 
1310 	if (ic->ic_max_rssi)
1311 		min_5ghz_rssi = IEEE80211_RSSI_THRES_RATIO_5GHZ;
1312 	else
1313 		min_5ghz_rssi = (uint8_t)IEEE80211_RSSI_THRES_5GHZ;
1314 
1315 	/*
1316 	 * Prefer a 5Ghz AP even if its RSSI is weaker than the best 2Ghz AP
1317 	 * (as long as it meets the minimum RSSI threshold) since the 5Ghz band
1318 	 * is usually less saturated.
1319 	 */
1320 	if (selbs5 && selbs5->ni_rssi > min_5ghz_rssi)
1321 		selbs = selbs5;
1322 	else if (selbs5 && selbs2)
1323 		selbs = (selbs5->ni_rssi >= selbs2->ni_rssi ? selbs5 : selbs2);
1324 	else if (selbs2)
1325 		selbs = selbs2;
1326 	else if (selbs5)
1327 		selbs = selbs5;
1328 
1329 	return selbs;
1330 }
1331 
1332 /*
1333  * Complete a scan of potential channels.
1334  */
1335 void
1336 ieee80211_end_scan(struct ifnet *ifp)
1337 {
1338 	struct ieee80211com *ic = (void *)ifp;
1339 	struct ieee80211_node *ni, *selbs = NULL, *curbs = NULL;
1340 	int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
1341 	    ic->ic_opmode == IEEE80211_M_STA &&
1342 	    ic->ic_state == IEEE80211_S_RUN);
1343 
1344 	if (ifp->if_flags & IFF_DEBUG)
1345 		printf("%s: end %s scan\n", ifp->if_xname,
1346 		    bgscan ? "background" :
1347 		    ((ic->ic_flags & IEEE80211_F_ASCAN) ?
1348 		    "active" : "passive"));
1349 
1350 	if (ic->ic_scan_count)
1351 		ic->ic_flags &= ~IEEE80211_F_ASCAN;
1352 
1353 	if (ic->ic_opmode == IEEE80211_M_STA)
1354 		ieee80211_clean_inactive_nodes(ic, IEEE80211_INACT_SCAN);
1355 
1356 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1357 
1358 #ifndef IEEE80211_STA_ONLY
1359 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1360 		/* XXX off stack? */
1361 		u_char occupied[howmany(IEEE80211_CHAN_MAX, NBBY)];
1362 		int i, fail;
1363 
1364 		/*
1365 		 * The passive scan to look for existing AP's completed,
1366 		 * select a channel to camp on.  Identify the channels
1367 		 * that already have one or more AP's and try to locate
1368 		 * an unoccupied one.  If that fails, pick a random
1369 		 * channel from the active set.
1370 		 */
1371 		memset(occupied, 0, sizeof(occupied));
1372 		RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
1373 			setbit(occupied, ieee80211_chan2ieee(ic, ni->ni_chan));
1374 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
1375 			if (isset(ic->ic_chan_active, i) && isclr(occupied, i))
1376 				break;
1377 		if (i == IEEE80211_CHAN_MAX) {
1378 			fail = arc4random() & 3;	/* random 0-3 */
1379 			for (i = 0; i < IEEE80211_CHAN_MAX; i++)
1380 				if (isset(ic->ic_chan_active, i) && fail-- == 0)
1381 					break;
1382 		}
1383 		ieee80211_create_ibss(ic, &ic->ic_channels[i]);
1384 		return;
1385 	}
1386 #endif
1387 	if (ni == NULL) {
1388 		DPRINTF(("no scan candidate\n"));
1389  notfound:
1390 
1391 #ifndef IEEE80211_STA_ONLY
1392 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
1393 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
1394 		    ic->ic_des_esslen != 0) {
1395 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
1396 			return;
1397 		}
1398 #endif
1399 		/*
1400 		 * Reset the list of channels to scan and scan the next mode
1401 		 * if nothing has been found.
1402 		 * If the device scans all bands in one fell swoop, return
1403 		 * current scan results to userspace regardless of mode.
1404 		 * This will loop forever until an access point is found.
1405 		 */
1406 		ieee80211_reset_scan(ifp);
1407 		if (ieee80211_next_mode(ifp) == IEEE80211_MODE_AUTO ||
1408 		    (ic->ic_caps & IEEE80211_C_SCANALLBAND))
1409 			ic->ic_scan_count++;
1410 
1411 		ieee80211_next_scan(ifp);
1412 		return;
1413 	}
1414 
1415 	/* Possibly switch which ssid we are associated with */
1416 	if (!bgscan && ic->ic_opmode == IEEE80211_M_STA)
1417 		ieee80211_switch_ess(ic);
1418 
1419 	selbs = ieee80211_node_choose_bss(ic, bgscan, &curbs);
1420 	if (bgscan) {
1421 		struct ieee80211_node_switch_bss_arg *arg;
1422 
1423 		/* AP disappeared? Should not happen. */
1424 		if (selbs == NULL || curbs == NULL) {
1425 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1426 			goto notfound;
1427 		}
1428 
1429 		/*
1430 		 * After a background scan we might end up choosing the
1431 		 * same AP again. Or the newly selected AP's RSSI level
1432 		 * might be low enough to trigger another background scan.
1433 		 * Do not change ic->ic_bss in these cases and make
1434 		 * background scans less frequent.
1435 		 */
1436 		if (selbs == curbs || !(*ic->ic_node_checkrssi)(ic, selbs)) {
1437 			if (ic->ic_bgscan_fail < IEEE80211_BGSCAN_FAIL_MAX) {
1438 				if (ic->ic_bgscan_fail <= 0)
1439 					ic->ic_bgscan_fail = 1;
1440 				else
1441 					ic->ic_bgscan_fail *= 2;
1442 			}
1443 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1444 
1445 			/*
1446 			 * HT is negotiated during association so we must use
1447 			 * ic_bss to check HT. The nodes tree was re-populated
1448 			 * during background scan and therefore selbs and curbs
1449 			 * may not carry HT information.
1450 			 */
1451 			ni = ic->ic_bss;
1452 			if (ni->ni_flags & IEEE80211_NODE_VHT)
1453 				ieee80211_setmode(ic, IEEE80211_MODE_11AC);
1454 			else if (ni->ni_flags & IEEE80211_NODE_HT)
1455 				ieee80211_setmode(ic, IEEE80211_MODE_11N);
1456 			else
1457 				ieee80211_setmode(ic,
1458 				    ieee80211_chan2mode(ic, ni->ni_chan));
1459 			return;
1460 		}
1461 
1462 		arg = malloc(sizeof(*arg), M_DEVBUF, M_NOWAIT | M_ZERO);
1463 		if (arg == NULL) {
1464 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1465 			return;
1466 		}
1467 
1468 		ic->ic_bgscan_fail = 0;
1469 
1470 		/*
1471 		 * We are going to switch APs. Stop A-MPDU Tx and
1472 		 * queue a de-auth frame addressed to our current AP.
1473 		 */
1474 		 ieee80211_stop_ampdu_tx(ic, ic->ic_bss,
1475 		    IEEE80211_FC0_SUBTYPE_DEAUTH);
1476 		if (IEEE80211_SEND_MGMT(ic, ic->ic_bss,
1477 		    IEEE80211_FC0_SUBTYPE_DEAUTH,
1478 		    IEEE80211_REASON_AUTH_LEAVE) != 0) {
1479 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1480 			free(arg, M_DEVBUF, sizeof(*arg));
1481 			return;
1482 		}
1483 
1484 		/* Prevent dispatch of additional data frames to hardware. */
1485 		ic->ic_xflags |= IEEE80211_F_TX_MGMT_ONLY;
1486 
1487 		/*
1488 		 * Install a callback which will switch us to the new AP once
1489 		 * all dispatched frames have been processed by hardware.
1490 		 */
1491 		IEEE80211_ADDR_COPY(arg->cur_macaddr, curbs->ni_macaddr);
1492 		IEEE80211_ADDR_COPY(arg->sel_macaddr, selbs->ni_macaddr);
1493 		ic->ic_bss->ni_unref_arg = arg;
1494 		ic->ic_bss->ni_unref_arg_size = sizeof(*arg);
1495 		ic->ic_bss->ni_unref_cb = ieee80211_node_switch_bss;
1496 		/* F_BGSCAN flag gets cleared in ieee80211_node_join_bss(). */
1497 		return;
1498 	} else if (selbs == NULL)
1499 		goto notfound;
1500 
1501 	ieee80211_node_join_bss(ic, selbs);
1502 }
1503 
1504 /*
1505  * Autoselect the best RSN parameters (protocol, AKMP, pairwise cipher...)
1506  * that are supported by both peers (STA mode only).
1507  */
1508 void
1509 ieee80211_choose_rsnparams(struct ieee80211com *ic)
1510 {
1511 	struct ieee80211_node *ni = ic->ic_bss;
1512 	struct ieee80211_pmk *pmk;
1513 
1514 	/* filter out unsupported protocol versions */
1515 	ni->ni_rsnprotos &= ic->ic_rsnprotos;
1516 	/* prefer RSN (aka WPA2) over WPA */
1517 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
1518 		ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
1519 	else
1520 		ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
1521 
1522 	/* filter out unsupported AKMPs */
1523 	ni->ni_rsnakms &= ic->ic_rsnakms;
1524 	/* prefer SHA-256 based AKMPs */
1525 	if ((ic->ic_flags & IEEE80211_F_PSK) && (ni->ni_rsnakms &
1526 	    (IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK))) {
1527 		/* AP supports PSK AKMP and a PSK is configured */
1528 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_PSK)
1529 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_PSK;
1530 		else
1531 			ni->ni_rsnakms = IEEE80211_AKM_PSK;
1532 	} else {
1533 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_8021X)
1534 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_8021X;
1535 		else
1536 			ni->ni_rsnakms = IEEE80211_AKM_8021X;
1537 		/* check if we have a cached PMK for this AP */
1538 		if (ni->ni_rsnprotos == IEEE80211_PROTO_RSN &&
1539 		    (pmk = ieee80211_pmksa_find(ic, ni, NULL)) != NULL) {
1540 			memcpy(ni->ni_pmkid, pmk->pmk_pmkid,
1541 			    IEEE80211_PMKID_LEN);
1542 			ni->ni_flags |= IEEE80211_NODE_PMKID;
1543 		}
1544 	}
1545 
1546 	/* filter out unsupported pairwise ciphers */
1547 	ni->ni_rsnciphers &= ic->ic_rsnciphers;
1548 	/* prefer CCMP over TKIP */
1549 	if (ni->ni_rsnciphers & IEEE80211_CIPHER_CCMP)
1550 		ni->ni_rsnciphers = IEEE80211_CIPHER_CCMP;
1551 	else
1552 		ni->ni_rsnciphers = IEEE80211_CIPHER_TKIP;
1553 	ni->ni_rsncipher = ni->ni_rsnciphers;
1554 
1555 	/* use MFP if we both support it */
1556 	if ((ic->ic_caps & IEEE80211_C_MFP) &&
1557 	    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
1558 		ni->ni_flags |= IEEE80211_NODE_MFP;
1559 }
1560 
1561 int
1562 ieee80211_get_rate(struct ieee80211com *ic)
1563 {
1564 	u_int8_t (*rates)[IEEE80211_RATE_MAXSIZE];
1565 	int rate;
1566 
1567 	rates = &ic->ic_bss->ni_rates.rs_rates;
1568 
1569 	if (ic->ic_fixed_rate != -1)
1570 		rate = (*rates)[ic->ic_fixed_rate];
1571 	else if (ic->ic_state == IEEE80211_S_RUN)
1572 		rate = (*rates)[ic->ic_bss->ni_txrate];
1573 	else
1574 		rate = 0;
1575 
1576 	return rate & IEEE80211_RATE_VAL;
1577 }
1578 
1579 struct ieee80211_node *
1580 ieee80211_node_alloc(struct ieee80211com *ic)
1581 {
1582 	return malloc(sizeof(struct ieee80211_node), M_DEVBUF,
1583 	    M_NOWAIT | M_ZERO);
1584 }
1585 
1586 void
1587 ieee80211_node_cleanup(struct ieee80211com *ic, struct ieee80211_node *ni)
1588 {
1589 	if (ni->ni_rsnie != NULL) {
1590 		free(ni->ni_rsnie, M_DEVBUF, 2 + ni->ni_rsnie[1]);
1591 		ni->ni_rsnie = NULL;
1592 	}
1593 	ieee80211_ba_del(ni);
1594 	ni->ni_unref_cb = NULL;
1595 	free(ni->ni_unref_arg, M_DEVBUF, ni->ni_unref_arg_size);
1596 	ni->ni_unref_arg = NULL;
1597 	ni->ni_unref_arg_size = 0;
1598 
1599 #ifndef IEEE80211_STA_ONLY
1600 	mq_purge(&ni->ni_savedq);
1601 #endif
1602 }
1603 
1604 void
1605 ieee80211_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
1606 {
1607 	ieee80211_node_cleanup(ic, ni);
1608 	free(ni, M_DEVBUF, 0);
1609 }
1610 
1611 void
1612 ieee80211_node_copy(struct ieee80211com *ic,
1613 	struct ieee80211_node *dst, const struct ieee80211_node *src)
1614 {
1615 	ieee80211_node_cleanup(ic, dst);
1616 	*dst = *src;
1617 	dst->ni_rsnie = NULL;
1618 	if (src->ni_rsnie != NULL)
1619 		ieee80211_save_ie(src->ni_rsnie, &dst->ni_rsnie);
1620 	ieee80211_node_set_timeouts(dst);
1621 #ifndef IEEE80211_STA_ONLY
1622 	mq_init(&dst->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
1623 #endif
1624 }
1625 
1626 u_int8_t
1627 ieee80211_node_getrssi(struct ieee80211com *ic,
1628     const struct ieee80211_node *ni)
1629 {
1630 	return ni->ni_rssi;
1631 }
1632 
1633 int
1634 ieee80211_node_checkrssi(struct ieee80211com *ic,
1635     const struct ieee80211_node *ni)
1636 {
1637 	uint8_t thres;
1638 
1639 	if (ni->ni_chan == IEEE80211_CHAN_ANYC)
1640 		return 0;
1641 
1642 	if (ic->ic_max_rssi) {
1643 		thres = (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) ?
1644 		    IEEE80211_RSSI_THRES_RATIO_2GHZ :
1645 		    IEEE80211_RSSI_THRES_RATIO_5GHZ;
1646 		return ((ni->ni_rssi * 100) / ic->ic_max_rssi >= thres);
1647 	}
1648 
1649 	thres = (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) ?
1650 	    IEEE80211_RSSI_THRES_2GHZ :
1651 	    IEEE80211_RSSI_THRES_5GHZ;
1652 	return (ni->ni_rssi >= (u_int8_t)thres);
1653 }
1654 
1655 void
1656 ieee80211_node_set_timeouts(struct ieee80211_node *ni)
1657 {
1658 	int i;
1659 
1660 #ifndef IEEE80211_STA_ONLY
1661 	timeout_set(&ni->ni_eapol_to, ieee80211_eapol_timeout, ni);
1662 	timeout_set(&ni->ni_sa_query_to, ieee80211_sa_query_timeout, ni);
1663 #endif
1664 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_BE],
1665 	    ieee80211_node_addba_request_ac_be_to, ni);
1666 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_BK],
1667 	    ieee80211_node_addba_request_ac_bk_to, ni);
1668 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_VI],
1669 	    ieee80211_node_addba_request_ac_vi_to, ni);
1670 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_VO],
1671 	    ieee80211_node_addba_request_ac_vo_to, ni);
1672 	for (i = 0; i < nitems(ni->ni_addba_req_intval); i++)
1673 		ni->ni_addba_req_intval[i] = 1;
1674 }
1675 
1676 void
1677 ieee80211_setup_node(struct ieee80211com *ic,
1678 	struct ieee80211_node *ni, const u_int8_t *macaddr)
1679 {
1680 	int i, s;
1681 
1682 	DPRINTF(("%s\n", ether_sprintf((u_int8_t *)macaddr)));
1683 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1684 	ieee80211_node_newstate(ni, IEEE80211_STA_CACHE);
1685 
1686 	ni->ni_ic = ic;	/* back-pointer */
1687 	/* Initialize cached last sequence numbers with invalid values. */
1688 	ni->ni_rxseq = 0xffffU;
1689 	for (i=0; i < IEEE80211_NUM_TID; ++i)
1690 		ni->ni_qos_rxseqs[i] = 0xffffU;
1691 #ifndef IEEE80211_STA_ONLY
1692 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
1693 #endif
1694 	ieee80211_node_set_timeouts(ni);
1695 
1696 	s = splnet();
1697 	RBT_INSERT(ieee80211_tree, &ic->ic_tree, ni);
1698 	ic->ic_nnodes++;
1699 	splx(s);
1700 }
1701 
1702 struct ieee80211_node *
1703 ieee80211_alloc_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1704 {
1705 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
1706 	if (ni != NULL)
1707 		ieee80211_setup_node(ic, ni, macaddr);
1708 	else
1709 		ic->ic_stats.is_rx_nodealloc++;
1710 	return ni;
1711 }
1712 
1713 struct ieee80211_node *
1714 ieee80211_dup_bss(struct ieee80211com *ic, const u_int8_t *macaddr)
1715 {
1716 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
1717 	if (ni != NULL) {
1718 		ieee80211_setup_node(ic, ni, macaddr);
1719 		/*
1720 		 * Inherit from ic_bss.
1721 		 */
1722 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1723 		ni->ni_chan = ic->ic_bss->ni_chan;
1724 	} else
1725 		ic->ic_stats.is_rx_nodealloc++;
1726 	return ni;
1727 }
1728 
1729 struct ieee80211_node *
1730 ieee80211_find_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1731 {
1732 	struct ieee80211_node *ni;
1733 	int cmp;
1734 
1735 	/* similar to RBT_FIND except we compare keys, not nodes */
1736 	ni = RBT_ROOT(ieee80211_tree, &ic->ic_tree);
1737 	while (ni != NULL) {
1738 		cmp = memcmp(macaddr, ni->ni_macaddr, IEEE80211_ADDR_LEN);
1739 		if (cmp < 0)
1740 			ni = RBT_LEFT(ieee80211_tree, ni);
1741 		else if (cmp > 0)
1742 			ni = RBT_RIGHT(ieee80211_tree, ni);
1743 		else
1744 			break;
1745 	}
1746 	return ni;
1747 }
1748 
1749 /*
1750  * Return a reference to the appropriate node for sending
1751  * a data frame.  This handles node discovery in adhoc networks.
1752  *
1753  * Drivers will call this, so increase the reference count before
1754  * returning the node.
1755  */
1756 struct ieee80211_node *
1757 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1758 {
1759 #ifndef IEEE80211_STA_ONLY
1760 	struct ieee80211_node *ni;
1761 	int s;
1762 #endif
1763 
1764 	/*
1765 	 * The destination address should be in the node table
1766 	 * unless we are operating in station mode or this is a
1767 	 * multicast/broadcast frame.
1768 	 */
1769 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1770 		return ieee80211_ref_node(ic->ic_bss);
1771 
1772 #ifndef IEEE80211_STA_ONLY
1773 	s = splnet();
1774 	ni = ieee80211_find_node(ic, macaddr);
1775 	splx(s);
1776 	if (ni == NULL) {
1777 		if (ic->ic_opmode != IEEE80211_M_IBSS &&
1778 		    ic->ic_opmode != IEEE80211_M_AHDEMO)
1779 			return NULL;
1780 
1781 		/*
1782 		 * Fake up a node; this handles node discovery in
1783 		 * adhoc mode.  Note that for the driver's benefit
1784 		 * we we treat this like an association so the driver
1785 		 * has an opportunity to setup its private state.
1786 		 *
1787 		 * XXX need better way to handle this; issue probe
1788 		 *     request so we can deduce rate set, etc.
1789 		 */
1790 		if ((ni = ieee80211_dup_bss(ic, macaddr)) == NULL)
1791 			return NULL;
1792 		/* XXX no rate negotiation; just dup */
1793 		ni->ni_rates = ic->ic_bss->ni_rates;
1794 		ni->ni_txrate = 0;
1795 		if (ic->ic_newassoc)
1796 			(*ic->ic_newassoc)(ic, ni, 1);
1797 	}
1798 	return ieee80211_ref_node(ni);
1799 #else
1800 	return NULL;	/* can't get there */
1801 #endif	/* IEEE80211_STA_ONLY */
1802 }
1803 
1804 /*
1805  * It is usually desirable to process a Rx packet using its sender's
1806  * node-record instead of the BSS record.
1807  *
1808  * - AP mode: keep a node-record for every authenticated/associated
1809  *   station *in the BSS*. For future use, we also track neighboring
1810  *   APs, since they might belong to the same ESS.  APs in the same
1811  *   ESS may bridge packets to each other, forming a Wireless
1812  *   Distribution System (WDS).
1813  *
1814  * - IBSS mode: keep a node-record for every station *in the BSS*.
1815  *   Also track neighboring stations by their beacons/probe responses.
1816  *
1817  * - monitor mode: keep a node-record for every sender, regardless
1818  *   of BSS.
1819  *
1820  * - STA mode: the only available node-record is the BSS record,
1821  *   ic->ic_bss.
1822  *
1823  * Of all the 802.11 Control packets, only the node-records for
1824  * RTS packets node-record can be looked up.
1825  *
1826  * Return non-zero if the packet's node-record is kept, zero
1827  * otherwise.
1828  */
1829 static __inline int
1830 ieee80211_needs_rxnode(struct ieee80211com *ic,
1831     const struct ieee80211_frame *wh, const u_int8_t **bssid)
1832 {
1833 	int monitor, rc = 0;
1834 
1835 	monitor = (ic->ic_opmode == IEEE80211_M_MONITOR);
1836 
1837 	*bssid = NULL;
1838 
1839 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1840 	case IEEE80211_FC0_TYPE_CTL:
1841 		if (!monitor)
1842 			break;
1843 		return (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1844 		    IEEE80211_FC0_SUBTYPE_RTS;
1845 	case IEEE80211_FC0_TYPE_MGT:
1846 		*bssid = wh->i_addr3;
1847 		switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
1848 		case IEEE80211_FC0_SUBTYPE_BEACON:
1849 		case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1850 			break;
1851 		default:
1852 #ifndef IEEE80211_STA_ONLY
1853 			if (ic->ic_opmode == IEEE80211_M_STA)
1854 				break;
1855 			rc = IEEE80211_ADDR_EQ(*bssid, ic->ic_bss->ni_bssid) ||
1856 			     IEEE80211_ADDR_EQ(*bssid, etherbroadcastaddr);
1857 #endif
1858 			break;
1859 		}
1860 		break;
1861 	case IEEE80211_FC0_TYPE_DATA:
1862 		switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
1863 		case IEEE80211_FC1_DIR_NODS:
1864 			*bssid = wh->i_addr3;
1865 #ifndef IEEE80211_STA_ONLY
1866 			if (ic->ic_opmode == IEEE80211_M_IBSS ||
1867 			    ic->ic_opmode == IEEE80211_M_AHDEMO)
1868 				rc = IEEE80211_ADDR_EQ(*bssid,
1869 				    ic->ic_bss->ni_bssid);
1870 #endif
1871 			break;
1872 		case IEEE80211_FC1_DIR_TODS:
1873 			*bssid = wh->i_addr1;
1874 #ifndef IEEE80211_STA_ONLY
1875 			if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1876 				rc = IEEE80211_ADDR_EQ(*bssid,
1877 				    ic->ic_bss->ni_bssid);
1878 #endif
1879 			break;
1880 		case IEEE80211_FC1_DIR_FROMDS:
1881 		case IEEE80211_FC1_DIR_DSTODS:
1882 			*bssid = wh->i_addr2;
1883 #ifndef IEEE80211_STA_ONLY
1884 			rc = (ic->ic_opmode == IEEE80211_M_HOSTAP);
1885 #endif
1886 			break;
1887 		}
1888 		break;
1889 	}
1890 	return monitor || rc;
1891 }
1892 
1893 /*
1894  * Drivers call this, so increase the reference count before returning
1895  * the node.
1896  */
1897 struct ieee80211_node *
1898 ieee80211_find_rxnode(struct ieee80211com *ic,
1899     const struct ieee80211_frame *wh)
1900 {
1901 	static const u_int8_t zero[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1902 	struct ieee80211_node *ni;
1903 	const u_int8_t *bssid;
1904 	int s;
1905 
1906 	if (!ieee80211_needs_rxnode(ic, wh, &bssid))
1907 		return ieee80211_ref_node(ic->ic_bss);
1908 
1909 	s = splnet();
1910 	ni = ieee80211_find_node(ic, wh->i_addr2);
1911 	splx(s);
1912 
1913 	if (ni != NULL)
1914 		return ieee80211_ref_node(ni);
1915 #ifndef IEEE80211_STA_ONLY
1916 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1917 		return ieee80211_ref_node(ic->ic_bss);
1918 #endif
1919 	/* XXX see remarks in ieee80211_find_txnode */
1920 	/* XXX no rate negotiation; just dup */
1921 	if ((ni = ieee80211_dup_bss(ic, wh->i_addr2)) == NULL)
1922 		return ieee80211_ref_node(ic->ic_bss);
1923 
1924 	IEEE80211_ADDR_COPY(ni->ni_bssid, (bssid != NULL) ? bssid : zero);
1925 
1926 	ni->ni_rates = ic->ic_bss->ni_rates;
1927 	ni->ni_txrate = 0;
1928 	if (ic->ic_newassoc)
1929 		(*ic->ic_newassoc)(ic, ni, 1);
1930 
1931 	DPRINTF(("faked-up node %p for %s\n", ni,
1932 	    ether_sprintf((u_int8_t *)wh->i_addr2)));
1933 
1934 	return ieee80211_ref_node(ni);
1935 }
1936 
1937 struct ieee80211_node *
1938 ieee80211_find_node_for_beacon(struct ieee80211com *ic,
1939     const u_int8_t *macaddr, const struct ieee80211_channel *chan,
1940     const char *ssid, u_int8_t rssi)
1941 {
1942 	struct ieee80211_node *ni, *keep = NULL;
1943 	int s, score = 0;
1944 
1945 	if ((ni = ieee80211_find_node(ic, macaddr)) != NULL) {
1946 		s = splnet();
1947 
1948 		if (ni->ni_chan != chan && ni->ni_rssi >= rssi)
1949 			score++;
1950 		if (ssid[1] == 0 && ni->ni_esslen != 0)
1951 			score++;
1952 		if (score > 0)
1953 			keep = ni;
1954 
1955 		splx(s);
1956 	}
1957 
1958 	return (keep);
1959 }
1960 
1961 void
1962 ieee80211_ba_del(struct ieee80211_node *ni)
1963 {
1964 	int tid;
1965 
1966 	for (tid = 0; tid < nitems(ni->ni_rx_ba); tid++) {
1967 		struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
1968 		if (ba->ba_state != IEEE80211_BA_INIT) {
1969 			if (timeout_pending(&ba->ba_to))
1970 				timeout_del(&ba->ba_to);
1971 			if (timeout_pending(&ba->ba_gap_to))
1972 				timeout_del(&ba->ba_gap_to);
1973 			ba->ba_state = IEEE80211_BA_INIT;
1974 		}
1975 	}
1976 
1977 	for (tid = 0; tid < nitems(ni->ni_tx_ba); tid++) {
1978 		struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
1979 		if (ba->ba_state != IEEE80211_BA_INIT) {
1980 			if (timeout_pending(&ba->ba_to))
1981 				timeout_del(&ba->ba_to);
1982 			ba->ba_state = IEEE80211_BA_INIT;
1983 		}
1984 	}
1985 
1986 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_BE]);
1987 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_BK]);
1988 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_VI]);
1989 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_VO]);
1990 }
1991 
1992 void
1993 ieee80211_free_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1994 {
1995 	if (ni == ic->ic_bss)
1996 		panic("freeing bss node");
1997 
1998 	splassert(IPL_NET);
1999 
2000 	DPRINTF(("%s\n", ether_sprintf(ni->ni_macaddr)));
2001 #ifndef IEEE80211_STA_ONLY
2002 	timeout_del(&ni->ni_eapol_to);
2003 	timeout_del(&ni->ni_sa_query_to);
2004 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2005 #endif
2006 	ieee80211_ba_del(ni);
2007 	RBT_REMOVE(ieee80211_tree, &ic->ic_tree, ni);
2008 	ic->ic_nnodes--;
2009 #ifndef IEEE80211_STA_ONLY
2010 	if (mq_purge(&ni->ni_savedq) > 0) {
2011 		if (ic->ic_set_tim != NULL)
2012 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
2013 	}
2014 #endif
2015 	(*ic->ic_node_free)(ic, ni);
2016 	/* TBD indicate to drivers that a new node can be allocated */
2017 }
2018 
2019 void
2020 ieee80211_release_node(struct ieee80211com *ic, struct ieee80211_node *ni)
2021 {
2022 	int s;
2023 
2024 	DPRINTF(("%s refcnt %u\n", ether_sprintf(ni->ni_macaddr),
2025 	    ni->ni_refcnt));
2026 	s = splnet();
2027 	if (ieee80211_node_decref(ni) == 0) {
2028 		if (ni->ni_unref_cb) {
2029 			(*ni->ni_unref_cb)(ic, ni);
2030 			ni->ni_unref_cb = NULL;
2031  			/* Freed by callback if necessary: */
2032 			ni->ni_unref_arg = NULL;
2033 			ni->ni_unref_arg_size = 0;
2034 		}
2035 	    	if (ni->ni_state == IEEE80211_STA_COLLECT)
2036 			ieee80211_free_node(ic, ni);
2037 	}
2038 	splx(s);
2039 }
2040 
2041 void
2042 ieee80211_free_allnodes(struct ieee80211com *ic, int clear_ic_bss)
2043 {
2044 	struct ieee80211_node *ni;
2045 	int s;
2046 
2047 	DPRINTF(("freeing all nodes\n"));
2048 	s = splnet();
2049 	while ((ni = RBT_MIN(ieee80211_tree, &ic->ic_tree)) != NULL)
2050 		ieee80211_free_node(ic, ni);
2051 	splx(s);
2052 
2053 	if (clear_ic_bss && ic->ic_bss != NULL)
2054 		ieee80211_node_cleanup(ic, ic->ic_bss);
2055 }
2056 
2057 void
2058 ieee80211_clean_cached(struct ieee80211com *ic)
2059 {
2060 	struct ieee80211_node *ni, *next_ni;
2061 	int s;
2062 
2063 	s = splnet();
2064 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
2065 	    ni != NULL; ni = next_ni) {
2066 		next_ni = RBT_NEXT(ieee80211_tree, ni);
2067 		if (ni->ni_state == IEEE80211_STA_CACHE)
2068 			ieee80211_free_node(ic, ni);
2069 	}
2070 	splx(s);
2071 }
2072 /*
2073  * Timeout inactive nodes.
2074  *
2075  * If called because of a cache timeout, which happens only in hostap and ibss
2076  * modes, clean all inactive cached or authenticated nodes but don't de-auth
2077  * any associated nodes. Also update HT protection settings.
2078  *
2079  * Else, this function is called because a new node must be allocated but the
2080  * node cache is full. In this case, return as soon as a free slot was made
2081  * available. If acting as hostap, clean cached nodes regardless of their
2082  * recent activity and also allow de-authing of authenticated nodes older
2083  * than one cache wait interval, and de-authing of inactive associated nodes.
2084  */
2085 void
2086 ieee80211_clean_nodes(struct ieee80211com *ic, int cache_timeout)
2087 {
2088 	struct ieee80211_node *ni, *next_ni;
2089 	u_int gen = ic->ic_scangen++;		/* NB: ok 'cuz single-threaded*/
2090 	int s;
2091 #ifndef IEEE80211_STA_ONLY
2092 	int nnodes = 0, nonht = 0, nonhtassoc = 0;
2093 	struct ifnet *ifp = &ic->ic_if;
2094 	enum ieee80211_htprot htprot = IEEE80211_HTPROT_NONE;
2095 	enum ieee80211_protmode protmode = IEEE80211_PROT_NONE;
2096 #endif
2097 
2098 	s = splnet();
2099 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
2100 	    ni != NULL; ni = next_ni) {
2101 		next_ni = RBT_NEXT(ieee80211_tree, ni);
2102 		if (!cache_timeout && ic->ic_nnodes < ic->ic_max_nnodes)
2103 			break;
2104 		if (ni->ni_scangen == gen)	/* previously handled */
2105 			continue;
2106 #ifndef IEEE80211_STA_ONLY
2107 		nnodes++;
2108 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2109 			/*
2110 			 * Check if node supports 802.11n.
2111 			 * Only require HT capabilities IE for this check.
2112 			 * Nodes might never reveal their supported MCS to us
2113 			 * unless they go through a full association sequence.
2114 			 * ieee80211_node_supports_ht() could misclassify them.
2115 			 */
2116 			if ((ni->ni_flags & IEEE80211_NODE_HTCAP) == 0) {
2117 				nonht++;
2118 				if (ni->ni_state == IEEE80211_STA_ASSOC)
2119 					nonhtassoc++;
2120 			}
2121 		}
2122 #endif
2123 		ni->ni_scangen = gen;
2124 		if (ni->ni_refcnt > 0)
2125 			continue;
2126 #ifndef IEEE80211_STA_ONLY
2127 		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
2128 		    ic->ic_opmode == IEEE80211_M_IBSS) &&
2129 		    ic->ic_state == IEEE80211_S_RUN) {
2130 			if (cache_timeout) {
2131 				if (ni->ni_state != IEEE80211_STA_COLLECT &&
2132 				    (ni->ni_state == IEEE80211_STA_ASSOC ||
2133 				    ni->ni_inact < IEEE80211_INACT_MAX))
2134 					continue;
2135 			} else {
2136 				if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2137 				    ((ni->ni_state == IEEE80211_STA_ASSOC &&
2138 				    ni->ni_inact < IEEE80211_INACT_MAX) ||
2139 				    (ni->ni_state == IEEE80211_STA_AUTH &&
2140 				     ni->ni_inact == 0)))
2141 				    	continue;
2142 
2143 				if (ic->ic_opmode == IEEE80211_M_IBSS &&
2144 				    ni->ni_state != IEEE80211_STA_COLLECT &&
2145 				    ni->ni_state != IEEE80211_STA_CACHE &&
2146 				    ni->ni_inact < IEEE80211_INACT_MAX)
2147 					continue;
2148 			}
2149 		}
2150 		if (ifp->if_flags & IFF_DEBUG)
2151 			printf("%s: station %s purged from node cache\n",
2152 			    ifp->if_xname, ether_sprintf(ni->ni_macaddr));
2153 #endif
2154 		/*
2155 		 * If we're hostap and the node is authenticated, send
2156 		 * a deauthentication frame. The node will be freed when
2157 		 * the driver calls ieee80211_release_node().
2158 		 */
2159 #ifndef IEEE80211_STA_ONLY
2160 		nnodes--;
2161 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2162 			if ((ni->ni_flags & IEEE80211_NODE_HTCAP) == 0) {
2163 				nonht--;
2164 				if (ni->ni_state == IEEE80211_STA_ASSOC)
2165 					nonhtassoc--;
2166 			}
2167 		}
2168 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2169 		    ni->ni_state >= IEEE80211_STA_AUTH &&
2170 		    ni->ni_state != IEEE80211_STA_COLLECT) {
2171 			IEEE80211_SEND_MGMT(ic, ni,
2172 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2173 			    IEEE80211_REASON_AUTH_EXPIRE);
2174 			ieee80211_node_leave(ic, ni);
2175 		} else
2176 #endif
2177 			ieee80211_free_node(ic, ni);
2178 		ic->ic_stats.is_node_timeout++;
2179 	}
2180 
2181 #ifndef IEEE80211_STA_ONLY
2182 	if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2183 		uint16_t htop1 = ic->ic_bss->ni_htop1;
2184 
2185 		/* Update HT protection settings. */
2186 		if (nonht) {
2187 			protmode = IEEE80211_PROT_CTSONLY;
2188 			if (nonhtassoc)
2189 				htprot = IEEE80211_HTPROT_NONHT_MIXED;
2190 			else
2191 				htprot = IEEE80211_HTPROT_NONMEMBER;
2192 		}
2193 		if ((htop1 & IEEE80211_HTOP1_PROT_MASK) != htprot) {
2194 			htop1 &= ~IEEE80211_HTOP1_PROT_MASK;
2195 			htop1 |= htprot;
2196 			ic->ic_bss->ni_htop1 = htop1;
2197 			ic->ic_protmode = protmode;
2198 			if (ic->ic_update_htprot)
2199 				ic->ic_update_htprot(ic, ic->ic_bss);
2200 		}
2201 	}
2202 
2203 	/*
2204 	 * During a cache timeout we iterate over all nodes.
2205 	 * Check for node leaks by comparing the actual number of cached
2206 	 * nodes with the ic_nnodes count, which is maintained while adding
2207 	 * and removing nodes from the cache.
2208 	 */
2209 	if ((ifp->if_flags & IFF_DEBUG) && cache_timeout &&
2210 	    nnodes != ic->ic_nnodes)
2211 		printf("%s: number of cached nodes is %d, expected %d,"
2212 		    "possible nodes leak\n", ifp->if_xname, nnodes,
2213 		    ic->ic_nnodes);
2214 #endif
2215 	splx(s);
2216 }
2217 
2218 void
2219 ieee80211_clean_inactive_nodes(struct ieee80211com *ic, int inact_max)
2220 {
2221 	struct ieee80211_node *ni, *next_ni;
2222 	u_int gen = ic->ic_scangen++;	/* NB: ok 'cuz single-threaded*/
2223 	int s;
2224 
2225 	s = splnet();
2226 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
2227 	    ni != NULL; ni = next_ni) {
2228 		next_ni = RBT_NEXT(ieee80211_tree, ni);
2229 		if (ni->ni_scangen == gen)	/* previously handled */
2230 			continue;
2231 		ni->ni_scangen = gen;
2232 		if (ni->ni_refcnt > 0 || ni->ni_inact < inact_max)
2233 			continue;
2234 		ieee80211_free_node(ic, ni);
2235 		ic->ic_stats.is_node_timeout++;
2236 	}
2237 
2238 	splx(s);
2239 }
2240 
2241 void
2242 ieee80211_iterate_nodes(struct ieee80211com *ic, ieee80211_iter_func *f,
2243     void *arg)
2244 {
2245 	struct ieee80211_node *ni;
2246 	int s;
2247 
2248 	s = splnet();
2249 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
2250 		(*f)(arg, ni);
2251 	splx(s);
2252 }
2253 
2254 
2255 /*
2256  * Install received HT caps information in the node's state block.
2257  */
2258 void
2259 ieee80211_setup_htcaps(struct ieee80211_node *ni, const uint8_t *data,
2260     uint8_t len)
2261 {
2262 	uint16_t rxrate;
2263 
2264 	if (len != 26)
2265 		return;
2266 
2267 	ni->ni_htcaps = (data[0] | (data[1] << 8));
2268 	ni->ni_ampdu_param = data[2];
2269 
2270 	memcpy(ni->ni_rxmcs, &data[3], sizeof(ni->ni_rxmcs));
2271 	/* clear reserved bits */
2272 	clrbit(ni->ni_rxmcs, 77);
2273 	clrbit(ni->ni_rxmcs, 78);
2274 	clrbit(ni->ni_rxmcs, 79);
2275 
2276 	/* Max MCS Rx rate in 1Mb/s units (0 means "not specified"). */
2277 	rxrate = ((data[13] | (data[14]) << 8) & IEEE80211_MCS_RX_RATE_HIGH);
2278 	if (rxrate < 1024)
2279 		ni->ni_max_rxrate = rxrate;
2280 
2281 	ni->ni_tx_mcs_set = data[15];
2282 	ni->ni_htxcaps = (data[19] | (data[20] << 8));
2283 	ni->ni_txbfcaps = (data[21] | (data[22] << 8) | (data[23] << 16) |
2284 		(data[24] << 24));
2285 	ni->ni_aselcaps = data[25];
2286 
2287 	ni->ni_flags |= IEEE80211_NODE_HTCAP;
2288 }
2289 
2290 #ifndef IEEE80211_STA_ONLY
2291 /*
2292  * Handle nodes switching from 11n into legacy modes.
2293  */
2294 void
2295 ieee80211_clear_htcaps(struct ieee80211_node *ni)
2296 {
2297 	ni->ni_htcaps = 0;
2298 	ni->ni_ampdu_param = 0;
2299 	memset(ni->ni_rxmcs, 0, sizeof(ni->ni_rxmcs));
2300 	ni->ni_max_rxrate = 0;
2301 	ni->ni_tx_mcs_set = 0;
2302 	ni->ni_htxcaps = 0;
2303 	ni->ni_txbfcaps = 0;
2304 	ni->ni_aselcaps = 0;
2305 
2306 	ni->ni_flags &= ~(IEEE80211_NODE_HT | IEEE80211_NODE_HT_SGI20 |
2307 	    IEEE80211_NODE_HT_SGI40 | IEEE80211_NODE_HTCAP);
2308 
2309 }
2310 #endif
2311 
2312 /*
2313  * Install received HT op information in the node's state block.
2314  */
2315 int
2316 ieee80211_setup_htop(struct ieee80211_node *ni, const uint8_t *data,
2317     uint8_t len, int isprobe)
2318 {
2319 	if (len != 22)
2320 		return 0;
2321 
2322 	ni->ni_primary_chan = data[0]; /* XXX corresponds to ni_chan */
2323 
2324 	ni->ni_htop0 = data[1];
2325 	ni->ni_htop1 = (data[2] | (data[3] << 8));
2326 	ni->ni_htop2 = (data[3] | (data[4] << 8));
2327 
2328 	/*
2329 	 * According to 802.11-2012 Table 8-130 the Basic MCS set is
2330 	 * only "present in Beacon, Probe Response, Mesh Peering Open
2331 	 * and Mesh Peering Confirm frames. Otherwise reserved."
2332 	 */
2333 	if (isprobe)
2334 		memcpy(ni->ni_basic_mcs, &data[6], sizeof(ni->ni_basic_mcs));
2335 
2336 	return 1;
2337 }
2338 
2339 /*
2340  * Install received rate set information in the node's state block.
2341  */
2342 int
2343 ieee80211_setup_rates(struct ieee80211com *ic, struct ieee80211_node *ni,
2344     const u_int8_t *rates, const u_int8_t *xrates, int flags)
2345 {
2346 	struct ieee80211_rateset *rs = &ni->ni_rates;
2347 
2348 	memset(rs, 0, sizeof(*rs));
2349 	rs->rs_nrates = rates[1];
2350 	memcpy(rs->rs_rates, rates + 2, rs->rs_nrates);
2351 	if (xrates != NULL) {
2352 		u_int8_t nxrates;
2353 		/*
2354 		 * Tack on 11g extended supported rate element.
2355 		 */
2356 		nxrates = xrates[1];
2357 		if (rs->rs_nrates + nxrates > IEEE80211_RATE_MAXSIZE) {
2358 			nxrates = IEEE80211_RATE_MAXSIZE - rs->rs_nrates;
2359 			DPRINTF(("extended rate set too large; "
2360 			    "only using %u of %u rates\n",
2361 			    nxrates, xrates[1]));
2362 			ic->ic_stats.is_rx_rstoobig++;
2363 		}
2364 		memcpy(rs->rs_rates + rs->rs_nrates, xrates+2, nxrates);
2365 		rs->rs_nrates += nxrates;
2366 	}
2367 	return ieee80211_fix_rate(ic, ni, flags);
2368 }
2369 
2370 void
2371 ieee80211_node_trigger_addba_req(struct ieee80211_node *ni, int tid)
2372 {
2373 	if (ni->ni_tx_ba[tid].ba_state == IEEE80211_BA_INIT &&
2374 	    !timeout_pending(&ni->ni_addba_req_to[tid])) {
2375 		timeout_add_sec(&ni->ni_addba_req_to[tid],
2376 		    ni->ni_addba_req_intval[tid]);
2377 	}
2378 }
2379 
2380 void
2381 ieee80211_node_addba_request(struct ieee80211_node *ni, int tid)
2382 {
2383 	struct ieee80211com *ic = ni->ni_ic;
2384 	uint16_t ssn = ni->ni_qos_txseqs[tid];
2385 
2386 	ieee80211_addba_request(ic, ni, ssn, tid);
2387 }
2388 
2389 void
2390 ieee80211_node_addba_request_ac_be_to(void *arg)
2391 {
2392 	struct ieee80211_node *ni = arg;
2393 	ieee80211_node_addba_request(ni, EDCA_AC_BE);
2394 }
2395 
2396 void
2397 ieee80211_node_addba_request_ac_bk_to(void *arg)
2398 {
2399 	struct ieee80211_node *ni = arg;
2400 	ieee80211_node_addba_request(ni, EDCA_AC_BK);
2401 }
2402 
2403 void
2404 ieee80211_node_addba_request_ac_vi_to(void *arg)
2405 {
2406 	struct ieee80211_node *ni = arg;
2407 	ieee80211_node_addba_request(ni, EDCA_AC_VI);
2408 }
2409 
2410 void
2411 ieee80211_node_addba_request_ac_vo_to(void *arg)
2412 {
2413 	struct ieee80211_node *ni = arg;
2414 	ieee80211_node_addba_request(ni, EDCA_AC_VO);
2415 }
2416 
2417 #ifndef IEEE80211_STA_ONLY
2418 /*
2419  * Check if the specified node supports ERP.
2420  */
2421 int
2422 ieee80211_iserp_sta(const struct ieee80211_node *ni)
2423 {
2424 	static const u_int8_t rates[] = { 2, 4, 11, 22, 12, 24, 48 };
2425 	const struct ieee80211_rateset *rs = &ni->ni_rates;
2426 	int i, j;
2427 
2428 	/*
2429 	 * A STA supports ERP operation if it includes all the Clause 19
2430 	 * mandatory rates in its supported rate set.
2431 	 */
2432 	for (i = 0; i < nitems(rates); i++) {
2433 		for (j = 0; j < rs->rs_nrates; j++) {
2434 			if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == rates[i])
2435 				break;
2436 		}
2437 		if (j == rs->rs_nrates)
2438 			return 0;
2439 	}
2440 	return 1;
2441 }
2442 
2443 /*
2444  * This function is called to notify the 802.1X PACP machine that a new
2445  * 802.1X port is enabled and must be authenticated. For 802.11, a port
2446  * becomes enabled whenever a STA successfully completes Open System
2447  * authentication with an AP.
2448  */
2449 void
2450 ieee80211_needs_auth(struct ieee80211com *ic, struct ieee80211_node *ni)
2451 {
2452 	/*
2453 	 * XXX this could be done via the route socket of via a dedicated
2454 	 * EAP socket or another kernel->userland notification mechanism.
2455 	 * The notification should include the MAC address (ni_macaddr).
2456 	 */
2457 }
2458 
2459 /*
2460  * Handle an HT STA joining an HT network.
2461  */
2462 void
2463 ieee80211_node_join_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
2464 {
2465 	enum ieee80211_htprot;
2466 
2467 	/* Update HT protection setting. */
2468 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0) {
2469 		uint16_t htop1 = ic->ic_bss->ni_htop1;
2470 		htop1 &= ~IEEE80211_HTOP1_PROT_MASK;
2471 		htop1 |= IEEE80211_HTPROT_NONHT_MIXED;
2472 		ic->ic_bss->ni_htop1 = htop1;
2473 		if (ic->ic_update_htprot)
2474 			ic->ic_update_htprot(ic, ic->ic_bss);
2475 	}
2476 }
2477 
2478 /*
2479  * Handle a station joining an RSN network.
2480  */
2481 void
2482 ieee80211_node_join_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
2483 {
2484 	DPRINTF(("station %s associated using proto %d akm 0x%x "
2485 	    "cipher 0x%x groupcipher 0x%x\n", ether_sprintf(ni->ni_macaddr),
2486 	    ni->ni_rsnprotos, ni->ni_rsnakms, ni->ni_rsnciphers,
2487 	    ni->ni_rsngroupcipher));
2488 
2489 	ni->ni_rsn_state = RSNA_AUTHENTICATION;
2490 
2491 	ni->ni_key_count = 0;
2492 	ni->ni_port_valid = 0;
2493 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
2494 	ni->ni_flags &= ~IEEE80211_NODE_RSN_NEW_PTK;
2495 	ni->ni_replaycnt = -1;	/* XXX */
2496 	ni->ni_rsn_retries = 0;
2497 	ni->ni_rsncipher = ni->ni_rsnciphers;
2498 
2499 	ni->ni_rsn_state = RSNA_AUTHENTICATION_2;
2500 
2501 	/* generate a new authenticator nonce (ANonce) */
2502 	arc4random_buf(ni->ni_nonce, EAPOL_KEY_NONCE_LEN);
2503 
2504 	if (!ieee80211_is_8021x_akm(ni->ni_rsnakms)) {
2505 		memcpy(ni->ni_pmk, ic->ic_psk, IEEE80211_PMK_LEN);
2506 		ni->ni_flags |= IEEE80211_NODE_PMK;
2507 		(void)ieee80211_send_4way_msg1(ic, ni);
2508 	} else if (ni->ni_flags & IEEE80211_NODE_PMK) {
2509 		/* skip 802.1X auth if a cached PMK was found */
2510 		(void)ieee80211_send_4way_msg1(ic, ni);
2511 	} else {
2512 		/* no cached PMK found, needs full 802.1X auth */
2513 		ieee80211_needs_auth(ic, ni);
2514 	}
2515 }
2516 
2517 void
2518 ieee80211_count_longslotsta(void *arg, struct ieee80211_node *ni)
2519 {
2520 	int *longslotsta = arg;
2521 
2522 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2523 		return;
2524 
2525 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME))
2526 		(*longslotsta)++;
2527 }
2528 
2529 void
2530 ieee80211_count_nonerpsta(void *arg, struct ieee80211_node *ni)
2531 {
2532 	int *nonerpsta = arg;
2533 
2534 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2535 		return;
2536 
2537 	if (!ieee80211_iserp_sta(ni))
2538 		(*nonerpsta)++;
2539 }
2540 
2541 void
2542 ieee80211_count_pssta(void *arg, struct ieee80211_node *ni)
2543 {
2544 	int *pssta = arg;
2545 
2546 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2547 		return;
2548 
2549 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
2550 		(*pssta)++;
2551 }
2552 
2553 void
2554 ieee80211_count_rekeysta(void *arg, struct ieee80211_node *ni)
2555 {
2556 	int *rekeysta = arg;
2557 
2558 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2559 		return;
2560 
2561 	if (ni->ni_flags & IEEE80211_NODE_REKEY)
2562 		(*rekeysta)++;
2563 }
2564 
2565 /*
2566  * Handle a station joining an 11g network.
2567  */
2568 void
2569 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2570 {
2571 	int longslotsta = 0, nonerpsta = 0;
2572 
2573 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
2574 		/*
2575 		 * Joining STA doesn't support short slot time.  We must
2576 		 * disable the use of short slot time for all other associated
2577 		 * STAs and give the driver a chance to reconfigure the
2578 		 * hardware.
2579 		 */
2580 		ieee80211_iterate_nodes(ic,
2581 		    ieee80211_count_longslotsta, &longslotsta);
2582 		if (longslotsta == 1) {
2583 			if (ic->ic_caps & IEEE80211_C_SHSLOT)
2584 				ieee80211_set_shortslottime(ic, 0);
2585 		}
2586 		DPRINTF(("[%s] station needs long slot time, count %d\n",
2587 		    ether_sprintf(ni->ni_macaddr), longslotsta));
2588 	}
2589 
2590 	if (!ieee80211_iserp_sta(ni)) {
2591 		/*
2592 		 * Joining STA is non-ERP.
2593 		 */
2594 		ieee80211_iterate_nodes(ic,
2595 		    ieee80211_count_nonerpsta, &nonerpsta);
2596 		DPRINTF(("[%s] station is non-ERP, %d non-ERP "
2597 		    "stations associated\n", ether_sprintf(ni->ni_macaddr),
2598 		    nonerpsta));
2599 		/* must enable the use of protection */
2600 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2601 			DPRINTF(("enable use of protection\n"));
2602 			ic->ic_flags |= IEEE80211_F_USEPROT;
2603 		}
2604 
2605 		if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE))
2606 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2607 	} else
2608 		ni->ni_flags |= IEEE80211_NODE_ERP;
2609 }
2610 
2611 void
2612 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
2613     int resp)
2614 {
2615 	int newassoc = (ni->ni_state != IEEE80211_STA_ASSOC);
2616 
2617 	if (ni->ni_associd == 0) {
2618 		u_int16_t aid;
2619 
2620 		/*
2621 		 * It would be clever to search the bitmap
2622 		 * more efficiently, but this will do for now.
2623 		 */
2624 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2625 			if (!IEEE80211_AID_ISSET(aid,
2626 			    ic->ic_aid_bitmap))
2627 				break;
2628 		}
2629 		if (aid >= ic->ic_max_aid) {
2630 			IEEE80211_SEND_MGMT(ic, ni, resp,
2631 			    IEEE80211_REASON_ASSOC_TOOMANY);
2632 			ieee80211_node_leave(ic, ni);
2633 			return;
2634 		}
2635 		ni->ni_associd = aid | 0xc000;
2636 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2637 		if (ic->ic_curmode == IEEE80211_MODE_11G ||
2638 		    (ic->ic_curmode == IEEE80211_MODE_11N &&
2639 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
2640 			ieee80211_node_join_11g(ic, ni);
2641 	}
2642 
2643 	DPRINTF(("station %s %s associated at aid %d\n",
2644 	    ether_sprintf(ni->ni_macaddr), newassoc ? "newly" : "already",
2645 	    ni->ni_associd & ~0xc000));
2646 
2647 	ieee80211_ht_negotiate(ic, ni);
2648 	if (ic->ic_flags & IEEE80211_F_HTON)
2649 		ieee80211_node_join_ht(ic, ni);
2650 
2651 	/* give driver a chance to setup state like ni_txrate */
2652 	if (ic->ic_newassoc)
2653 		(*ic->ic_newassoc)(ic, ni, newassoc);
2654 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2655 	ieee80211_node_newstate(ni, IEEE80211_STA_ASSOC);
2656 
2657 	if (!(ic->ic_flags & IEEE80211_F_RSNON)) {
2658 		ni->ni_port_valid = 1;
2659 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
2660 	} else
2661 		ieee80211_node_join_rsn(ic, ni);
2662 
2663 #if NBRIDGE > 0
2664 	/*
2665 	 * If the parent interface is a bridge port, learn
2666 	 * the node's address dynamically on this interface.
2667 	 */
2668 	if (ic->ic_if.if_bridgeidx != 0)
2669 		bridge_update(&ic->ic_if,
2670 		    (struct ether_addr *)ni->ni_macaddr, 0);
2671 #endif
2672 }
2673 
2674 /*
2675  * Handle an HT STA leaving an HT network.
2676  */
2677 void
2678 ieee80211_node_leave_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
2679 {
2680 	struct ieee80211_rx_ba *ba;
2681 	u_int8_t tid;
2682 	int i;
2683 
2684 	/* free all Block Ack records */
2685 	ieee80211_ba_del(ni);
2686 	for (tid = 0; tid < IEEE80211_NUM_TID; tid++) {
2687 		ba = &ni->ni_rx_ba[tid];
2688 		if (ba->ba_buf != NULL) {
2689 			for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
2690 				m_freem(ba->ba_buf[i].m);
2691 			free(ba->ba_buf, M_DEVBUF,
2692 			    IEEE80211_BA_MAX_WINSZ * sizeof(*ba->ba_buf));
2693 			ba->ba_buf = NULL;
2694 		}
2695 	}
2696 
2697 	ieee80211_clear_htcaps(ni);
2698 }
2699 
2700 /*
2701  * Handle a station leaving an RSN network.
2702  */
2703 void
2704 ieee80211_node_leave_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
2705 {
2706 	int rekeysta = 0;
2707 
2708 	ni->ni_rsn_state = RSNA_INITIALIZE;
2709 	if (ni->ni_flags & IEEE80211_NODE_REKEY) {
2710 		ni->ni_flags &= ~IEEE80211_NODE_REKEY;
2711 		ieee80211_iterate_nodes(ic,
2712 		    ieee80211_count_rekeysta, &rekeysta);
2713 		if (rekeysta == 0)
2714 			ieee80211_setkeysdone(ic);
2715 	}
2716 	ni->ni_flags &= ~IEEE80211_NODE_PMK;
2717 	ni->ni_rsn_gstate = RSNA_IDLE;
2718 
2719 	timeout_del(&ni->ni_eapol_to);
2720 	timeout_del(&ni->ni_sa_query_to);
2721 
2722 	ni->ni_rsn_retries = 0;
2723 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
2724 	ni->ni_port_valid = 0;
2725 	(*ic->ic_delete_key)(ic, ni, &ni->ni_pairwise_key);
2726 }
2727 
2728 /*
2729  * Handle a station leaving an 11g network.
2730  */
2731 void
2732 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2733 {
2734 	int longslotsta = 0, nonerpsta = 0;
2735 
2736 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
2737 		/* leaving STA did not support short slot time */
2738 		ieee80211_iterate_nodes(ic,
2739 		    ieee80211_count_longslotsta, &longslotsta);
2740 		if (longslotsta == 1) {
2741 			/*
2742 			 * All associated STAs now support short slot time, so
2743 			 * enable this feature and give the driver a chance to
2744 			 * reconfigure the hardware. Notice that IBSS always
2745 			 * use a long slot time.
2746 			 */
2747 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2748 			    ic->ic_opmode != IEEE80211_M_IBSS)
2749 				ieee80211_set_shortslottime(ic, 1);
2750 		}
2751 		DPRINTF(("[%s] long slot time station leaves, count %d\n",
2752 		    ether_sprintf(ni->ni_macaddr), longslotsta));
2753 	}
2754 
2755 	if (!(ni->ni_flags & IEEE80211_NODE_ERP)) {
2756 		/* leaving STA was non-ERP */
2757 		ieee80211_iterate_nodes(ic,
2758 		    ieee80211_count_nonerpsta, &nonerpsta);
2759 		if (nonerpsta == 1) {
2760 			/*
2761 			 * All associated STAs are now ERP capable, disable use
2762 			 * of protection and re-enable short preamble support.
2763 			 */
2764 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2765 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE)
2766 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2767 		}
2768 		DPRINTF(("[%s] non-ERP station leaves, count %d\n",
2769 		    ether_sprintf(ni->ni_macaddr), nonerpsta));
2770 	}
2771 }
2772 
2773 /*
2774  * Handle bookkeeping for station deauthentication/disassociation
2775  * when operating as an ap.
2776  */
2777 void
2778 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2779 {
2780 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2781 		panic("not in ap mode, mode %u", ic->ic_opmode);
2782 
2783 	if (ni->ni_state == IEEE80211_STA_COLLECT)
2784 		return;
2785 	/*
2786 	 * If node wasn't previously associated all we need to do is
2787 	 * reclaim the reference.
2788 	 */
2789 	if (ni->ni_associd == 0) {
2790 		ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
2791 		return;
2792 	}
2793 
2794 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
2795 		ni->ni_pwrsave = IEEE80211_PS_AWAKE;
2796 
2797 	if (mq_purge(&ni->ni_savedq) > 0) {
2798 		if (ic->ic_set_tim != NULL)
2799 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
2800 	}
2801 
2802 	if (ic->ic_flags & IEEE80211_F_RSNON)
2803 		ieee80211_node_leave_rsn(ic, ni);
2804 
2805 	if (ic->ic_curmode == IEEE80211_MODE_11G ||
2806 	    (ic->ic_curmode == IEEE80211_MODE_11N &&
2807 	    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
2808 		ieee80211_node_leave_11g(ic, ni);
2809 
2810 	if (ni->ni_flags & IEEE80211_NODE_HT)
2811 		ieee80211_node_leave_ht(ic, ni);
2812 
2813 	if (ic->ic_node_leave != NULL)
2814 		(*ic->ic_node_leave)(ic, ni);
2815 
2816 	ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
2817 
2818 #if NBRIDGE > 0
2819 	/*
2820 	 * If the parent interface is a bridge port, delete
2821 	 * any dynamically learned address for this node.
2822 	 */
2823 	if (ic->ic_if.if_bridgeidx != 0)
2824 		bridge_update(&ic->ic_if,
2825 		    (struct ether_addr *)ni->ni_macaddr, 1);
2826 #endif
2827 }
2828 
2829 static int
2830 ieee80211_do_slow_print(struct ieee80211com *ic, int *did_print)
2831 {
2832 	static const struct timeval merge_print_intvl = {
2833 		.tv_sec = 1, .tv_usec = 0
2834 	};
2835 	if ((ic->ic_if.if_flags & IFF_LINK0) == 0)
2836 		return 0;
2837 	if (!*did_print && (ic->ic_if.if_flags & IFF_DEBUG) == 0 &&
2838 	    !ratecheck(&ic->ic_last_merge_print, &merge_print_intvl))
2839 		return 0;
2840 
2841 	*did_print = 1;
2842 	return 1;
2843 }
2844 
2845 /* ieee80211_ibss_merge helps merge 802.11 ad hoc networks.  The
2846  * convention, set by the Wireless Ethernet Compatibility Alliance
2847  * (WECA), is that an 802.11 station will change its BSSID to match
2848  * the "oldest" 802.11 ad hoc network, on the same channel, that
2849  * has the station's desired SSID.  The "oldest" 802.11 network
2850  * sends beacons with the greatest TSF timestamp.
2851  *
2852  * Return ENETRESET if the BSSID changed, 0 otherwise.
2853  *
2854  * XXX Perhaps we should compensate for the time that elapses
2855  * between the MAC receiving the beacon and the host processing it
2856  * in ieee80211_ibss_merge.
2857  */
2858 int
2859 ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni,
2860     u_int64_t local_tsft)
2861 {
2862 	u_int64_t beacon_tsft;
2863 	int did_print = 0, sign;
2864 	union {
2865 		u_int64_t	word;
2866 		u_int8_t	tstamp[8];
2867 	} u;
2868 
2869 	/* ensure alignment */
2870 	(void)memcpy(&u, &ni->ni_tstamp[0], sizeof(u));
2871 	beacon_tsft = letoh64(u.word);
2872 
2873 	/* we are faster, let the other guy catch up */
2874 	if (beacon_tsft < local_tsft)
2875 		sign = -1;
2876 	else
2877 		sign = 1;
2878 
2879 	if (IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
2880 		if (!ieee80211_do_slow_print(ic, &did_print))
2881 			return 0;
2882 		printf("%s: tsft offset %s%llu\n", ic->ic_if.if_xname,
2883 		    (sign < 0) ? "-" : "",
2884 		    (sign < 0)
2885 			? (local_tsft - beacon_tsft)
2886 			: (beacon_tsft - local_tsft));
2887 		return 0;
2888 	}
2889 
2890 	if (sign < 0)
2891 		return 0;
2892 
2893 	if (ieee80211_match_bss(ic, ni, 0) != 0)
2894 		return 0;
2895 
2896 	if (ieee80211_do_slow_print(ic, &did_print)) {
2897 		printf("%s: ieee80211_ibss_merge: bssid mismatch %s\n",
2898 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
2899 		printf("%s: my tsft %llu beacon tsft %llu\n",
2900 		    ic->ic_if.if_xname, local_tsft, beacon_tsft);
2901 		printf("%s: sync TSF with %s\n",
2902 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_macaddr));
2903 	}
2904 
2905 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
2906 
2907 	/* negotiate rates with new IBSS */
2908 	ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
2909 	    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2910 	if (ni->ni_rates.rs_nrates == 0) {
2911 		if (ieee80211_do_slow_print(ic, &did_print)) {
2912 			printf("%s: rates mismatch, BSSID %s\n",
2913 			    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
2914 		}
2915 		return 0;
2916 	}
2917 
2918 	if (ieee80211_do_slow_print(ic, &did_print)) {
2919 		printf("%s: sync BSSID %s -> ",
2920 		    ic->ic_if.if_xname, ether_sprintf(ic->ic_bss->ni_bssid));
2921 		printf("%s ", ether_sprintf(ni->ni_bssid));
2922 		printf("(from %s)\n", ether_sprintf(ni->ni_macaddr));
2923 	}
2924 
2925 	ieee80211_node_newstate(ni, IEEE80211_STA_BSS);
2926 	(*ic->ic_node_copy)(ic, ic->ic_bss, ni);
2927 
2928 	return ENETRESET;
2929 }
2930 
2931 void
2932 ieee80211_set_tim(struct ieee80211com *ic, int aid, int set)
2933 {
2934 	if (set)
2935 		setbit(ic->ic_tim_bitmap, aid & ~0xc000);
2936 	else
2937 		clrbit(ic->ic_tim_bitmap, aid & ~0xc000);
2938 }
2939 
2940 /*
2941  * This function shall be called by drivers immediately after every DTIM.
2942  * Transmit all group addressed MSDUs buffered at the AP.
2943  */
2944 void
2945 ieee80211_notify_dtim(struct ieee80211com *ic)
2946 {
2947 	/* NB: group addressed MSDUs are buffered in ic_bss */
2948 	struct ieee80211_node *ni = ic->ic_bss;
2949 	struct ifnet *ifp = &ic->ic_if;
2950 	struct ieee80211_frame *wh;
2951 	struct mbuf *m;
2952 
2953 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP);
2954 
2955 	while ((m = mq_dequeue(&ni->ni_savedq)) != NULL) {
2956 		if (!mq_empty(&ni->ni_savedq)) {
2957 			/* more queued frames, set the more data bit */
2958 			wh = mtod(m, struct ieee80211_frame *);
2959 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
2960 		}
2961 		mq_enqueue(&ic->ic_pwrsaveq, m);
2962 		if_start(ifp);
2963 	}
2964 	/* XXX assumes everything has been sent */
2965 	ic->ic_tim_mcast_pending = 0;
2966 }
2967 #endif	/* IEEE80211_STA_ONLY */
2968 
2969 /*
2970  * Compare nodes in the tree by lladdr
2971  */
2972 int
2973 ieee80211_node_cmp(const struct ieee80211_node *b1,
2974     const struct ieee80211_node *b2)
2975 {
2976 	return (memcmp(b1->ni_macaddr, b2->ni_macaddr, IEEE80211_ADDR_LEN));
2977 }
2978 
2979 /*
2980  * Compare nodes in the tree by essid
2981  */
2982 int
2983 ieee80211_ess_cmp(const struct ieee80211_ess_rbt *b1,
2984     const struct ieee80211_ess_rbt *b2)
2985 {
2986 	return (memcmp(b1->essid, b2->essid, IEEE80211_NWID_LEN));
2987 }
2988 
2989 /*
2990  * Generate red-black tree function logic
2991  */
2992 RBT_GENERATE(ieee80211_tree, ieee80211_node, ni_node, ieee80211_node_cmp);
2993 RBT_GENERATE(ieee80211_ess_tree, ieee80211_ess_rbt, ess_rbt, ieee80211_ess_cmp);
2994