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