xref: /haiku/src/libs/compat/openbsd_wlan/net80211/ieee80211_input.c (revision b548e9131d5498b8150070a00a2a2271edd5a326)
1 /*	$OpenBSD: ieee80211_input.c,v 1.250 2023/01/09 00:22:47 daniel Exp $	*/
2 /*	$NetBSD: ieee80211_input.c,v 1.24 2004/05/31 11:12:24 dyoung Exp $	*/
3 
4 /*-
5  * Copyright (c) 2001 Atsushi Onoe
6  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
7  * Copyright (c) 2007-2009 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 "bpfilter.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/task.h>
46 
47 #include <net/if.h>
48 #include <net/if_dl.h>
49 #include <net/if_media.h>
50 #include <net/if_llc.h>
51 
52 #if NBPFILTER > 0
53 #include <net/bpf.h>
54 #endif
55 
56 #include <netinet/in.h>
57 #include <netinet/if_ether.h>
58 
59 #include <net80211/ieee80211_var.h>
60 #include <net80211/ieee80211_priv.h>
61 
62 struct	mbuf *ieee80211_input_hwdecrypt(struct ieee80211com *,
63 	    struct ieee80211_node *, struct mbuf *,
64 	    struct ieee80211_rxinfo *rxi);
65 struct	mbuf *ieee80211_defrag(struct ieee80211com *, struct mbuf *, int);
66 void	ieee80211_defrag_timeout(void *);
67 void	ieee80211_input_ba(struct ieee80211com *, struct mbuf *,
68 	    struct ieee80211_node *, int, struct ieee80211_rxinfo *,
69 	    struct mbuf_list *);
70 void	ieee80211_input_ba_flush(struct ieee80211com *, struct ieee80211_node *,
71 	    struct ieee80211_rx_ba *, struct mbuf_list *);
72 int	ieee80211_input_ba_gap_skip(struct ieee80211_rx_ba *);
73 void	ieee80211_input_ba_gap_timeout(void *arg);
74 void	ieee80211_ba_move_window(struct ieee80211com *,
75 	    struct ieee80211_node *, u_int8_t, u_int16_t, struct mbuf_list *);
76 void	ieee80211_input_ba_seq(struct ieee80211com *,
77 	    struct ieee80211_node *, uint8_t, uint16_t, struct mbuf_list *);
78 struct	mbuf *ieee80211_align_mbuf(struct mbuf *);
79 void	ieee80211_decap(struct ieee80211com *, struct mbuf *,
80 	    struct ieee80211_node *, int, struct mbuf_list *);
81 int	ieee80211_amsdu_decap_validate(struct ieee80211com *, struct mbuf *,
82 	    struct ieee80211_node *);
83 void	ieee80211_amsdu_decap(struct ieee80211com *, struct mbuf *,
84 	    struct ieee80211_node *, int, struct mbuf_list *);
85 void	ieee80211_enqueue_data(struct ieee80211com *, struct mbuf *,
86 	    struct ieee80211_node *, int, struct mbuf_list *);
87 int	ieee80211_parse_edca_params_body(struct ieee80211com *,
88 	    const u_int8_t *);
89 int	ieee80211_parse_edca_params(struct ieee80211com *, const u_int8_t *);
90 int	ieee80211_parse_wmm_params(struct ieee80211com *, const u_int8_t *);
91 enum	ieee80211_cipher ieee80211_parse_rsn_cipher(const u_int8_t *);
92 enum	ieee80211_akm ieee80211_parse_rsn_akm(const u_int8_t *);
93 int	ieee80211_parse_rsn_body(struct ieee80211com *, const u_int8_t *,
94 	    u_int, struct ieee80211_rsnparams *);
95 int	ieee80211_save_ie(const u_int8_t *, u_int8_t **);
96 void	ieee80211_recv_probe_resp(struct ieee80211com *, struct mbuf *,
97 	    struct ieee80211_node *, struct ieee80211_rxinfo *, int);
98 #ifndef IEEE80211_STA_ONLY
99 void	ieee80211_recv_probe_req(struct ieee80211com *, struct mbuf *,
100 	    struct ieee80211_node *, struct ieee80211_rxinfo *);
101 #endif
102 void	ieee80211_recv_auth(struct ieee80211com *, struct mbuf *,
103 	    struct ieee80211_node *, struct ieee80211_rxinfo *);
104 #ifndef IEEE80211_STA_ONLY
105 void	ieee80211_recv_assoc_req(struct ieee80211com *, struct mbuf *,
106 	    struct ieee80211_node *, struct ieee80211_rxinfo *, int);
107 #endif
108 void	ieee80211_recv_assoc_resp(struct ieee80211com *, struct mbuf *,
109 	    struct ieee80211_node *, int);
110 void	ieee80211_recv_deauth(struct ieee80211com *, struct mbuf *,
111 	    struct ieee80211_node *);
112 void	ieee80211_recv_disassoc(struct ieee80211com *, struct mbuf *,
113 	    struct ieee80211_node *);
114 void	ieee80211_recv_addba_req(struct ieee80211com *, struct mbuf *,
115 	    struct ieee80211_node *);
116 void	ieee80211_recv_addba_resp(struct ieee80211com *, struct mbuf *,
117 	    struct ieee80211_node *);
118 void	ieee80211_recv_delba(struct ieee80211com *, struct mbuf *,
119 	    struct ieee80211_node *);
120 void	ieee80211_recv_sa_query_req(struct ieee80211com *, struct mbuf *,
121 	    struct ieee80211_node *);
122 #ifndef IEEE80211_STA_ONLY
123 void	ieee80211_recv_sa_query_resp(struct ieee80211com *, struct mbuf *,
124 	    struct ieee80211_node *);
125 #endif
126 void	ieee80211_recv_action(struct ieee80211com *, struct mbuf *,
127 	    struct ieee80211_node *);
128 #ifndef IEEE80211_STA_ONLY
129 void	ieee80211_recv_pspoll(struct ieee80211com *, struct mbuf *,
130 	    struct ieee80211_node *);
131 #endif
132 void	ieee80211_recv_bar(struct ieee80211com *, struct mbuf *,
133 	    struct ieee80211_node *);
134 void	ieee80211_bar_tid(struct ieee80211com *, struct ieee80211_node *,
135 	    u_int8_t, u_int16_t);
136 
137 /*
138  * Retrieve the length in bytes of an 802.11 header.
139  */
140 u_int
141 ieee80211_get_hdrlen(const struct ieee80211_frame *wh)
142 {
143 	u_int size = sizeof(*wh);
144 
145 	/* NB: does not work with control frames */
146 	KASSERT(ieee80211_has_seq(wh));
147 
148 	if (ieee80211_has_addr4(wh))
149 		size += IEEE80211_ADDR_LEN;	/* i_addr4 */
150 	if (ieee80211_has_qos(wh))
151 		size += sizeof(u_int16_t);	/* i_qos */
152 	if (ieee80211_has_htc(wh))
153 		size += sizeof(u_int32_t);	/* i_ht */
154 	return size;
155 }
156 
157 /* Post-processing for drivers which perform decryption in hardware. */
158 struct mbuf *
159 ieee80211_input_hwdecrypt(struct ieee80211com *ic, struct ieee80211_node *ni,
160     struct mbuf *m, struct ieee80211_rxinfo *rxi)
161 {
162 	struct ieee80211_key *k;
163 	struct ieee80211_frame *wh;
164 	uint64_t pn, *prsc;
165 	int hdrlen;
166 
167 	k = ieee80211_get_rxkey(ic, m, ni);
168 	if (k == NULL)
169 		return NULL;
170 
171 	wh = mtod(m, struct ieee80211_frame *);
172 	hdrlen = ieee80211_get_hdrlen(wh);
173 
174 	/*
175 	 * Update the last-seen packet number (PN) for drivers using hardware
176 	 * crypto offloading. This cannot be done by drivers because A-MPDU
177 	 * reordering needs to occur before a valid lower bound can be
178 	 * determined for the PN. Drivers will read the PN we write here and
179 	 * are expected to discard replayed frames based on it.
180 	 * Drivers are expected to leave the IV of decrypted frames intact
181 	 * so we can update the last-seen PN and strip the IV here.
182 	 */
183 	switch (k->k_cipher) {
184 	case IEEE80211_CIPHER_CCMP:
185 		if (!(wh->i_fc[1] & IEEE80211_FC1_PROTECTED)) {
186 			/*
187 			 * If the protected bit is clear then hardware has
188 			 * stripped the IV and we must trust that it handles
189 			 * replay detection correctly.
190 			 */
191 			break;
192 		}
193 		if (ieee80211_ccmp_get_pn(&pn, &prsc, m, k) != 0)
194 			return NULL;
195 		if (rxi->rxi_flags & IEEE80211_RXI_HWDEC_SAME_PN) {
196 			if (pn < *prsc) {
197 				ic->ic_stats.is_ccmp_replays++;
198 				return NULL;
199 			}
200 		} else if (pn <= *prsc) {
201 			ic->ic_stats.is_ccmp_replays++;
202 			return NULL;
203 		}
204 
205 		/* Update last-seen packet number. */
206 		*prsc = pn;
207 
208 		/* Clear Protected bit and strip IV. */
209 		wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
210 		memmove(mtod(m, caddr_t) + IEEE80211_CCMP_HDRLEN, wh, hdrlen);
211 		m_adj(m, IEEE80211_CCMP_HDRLEN);
212 		/* Drivers are expected to strip the MIC. */
213 		break;
214 	 case IEEE80211_CIPHER_TKIP:
215 		if (!(wh->i_fc[1] & IEEE80211_FC1_PROTECTED)) {
216 			/*
217 			 * If the protected bit is clear then hardware has
218 			 * stripped the IV and we must trust that it handles
219 			 * replay detection correctly.
220 			 */
221 			break;
222 		}
223 		if (ieee80211_tkip_get_tsc(&pn, &prsc, m, k) != 0)
224 			return NULL;
225 		if (rxi->rxi_flags & IEEE80211_RXI_HWDEC_SAME_PN) {
226 			if (pn < *prsc) {
227 				ic->ic_stats.is_tkip_replays++;
228 				return NULL;
229 			}
230 		} else if (pn <= *prsc) {
231 			ic->ic_stats.is_tkip_replays++;
232 			return NULL;
233 		}
234 
235 		/* Update last-seen packet number. */
236 		*prsc = pn;
237 
238 		/* Clear Protected bit and strip IV. */
239 		wh = mtod(m, struct ieee80211_frame *);
240 		wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
241 		memmove(mtod(m, caddr_t) + IEEE80211_TKIP_HDRLEN, wh, hdrlen);
242 		m_adj(m, IEEE80211_TKIP_HDRLEN);
243 		/* Drivers are expected to strip the MIC. */
244 		break;
245 	default:
246 		break;
247 	}
248 
249 	return m;
250 }
251 
252 /*
253  * Process a received frame.  The node associated with the sender
254  * should be supplied.  If nothing was found in the node table then
255  * the caller is assumed to supply a reference to ic_bss instead.
256  * The RSSI and a timestamp are also supplied.  The RSSI data is used
257  * during AP scanning to select a AP to associate with; it can have
258  * any units so long as values have consistent units and higher values
259  * mean ``better signal''.  The receive timestamp is currently not used
260  * by the 802.11 layer.
261  *
262  * This function acts on management frames immediately and queues data frames
263  * on the specified mbuf list. Delivery of queued data frames to upper layers
264  * must be triggered with if_input(). Drivers should call if_input() only once
265  * per Rx interrupt to avoid triggering the input ifq pressure drop mechanism
266  * unnecessarily.
267  */
268 void
269 ieee80211_inputm(struct ifnet *ifp, struct mbuf *m, struct ieee80211_node *ni,
270     struct ieee80211_rxinfo *rxi, struct mbuf_list *ml)
271 {
272 	struct ieee80211com *ic = (void *)ifp;
273 	struct ieee80211_frame *wh;
274 	u_int16_t *orxseq, nrxseq, qos;
275 	u_int8_t dir, type, subtype, tid;
276 	int hdrlen, hasqos;
277 
278 	KASSERT(ni != NULL);
279 
280 	/* in monitor mode, send everything directly to bpf */
281 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
282 		goto out;
283 
284 	/*
285 	 * Do not process frames without an Address 2 field any further.
286 	 * Only CTS and ACK control frames do not have this field.
287 	 */
288 	if (m->m_len < sizeof(struct ieee80211_frame_min)) {
289 		DPRINTF(("frame too short, len %u\n", m->m_len));
290 		ic->ic_stats.is_rx_tooshort++;
291 		goto out;
292 	}
293 
294 	wh = mtod(m, struct ieee80211_frame *);
295 	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
296 	    IEEE80211_FC0_VERSION_0) {
297 		DPRINTF(("frame with wrong version: %x\n", wh->i_fc[0]));
298 		ic->ic_stats.is_rx_badversion++;
299 		goto err;
300 	}
301 
302 	dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
303 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
304 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
305 
306 	if (type != IEEE80211_FC0_TYPE_CTL) {
307 		hdrlen = ieee80211_get_hdrlen(wh);
308 		if (m->m_len < hdrlen) {
309 			DPRINTF(("frame too short, len %u\n", m->m_len));
310 			ic->ic_stats.is_rx_tooshort++;
311 			goto err;
312 		}
313 	} else
314 		hdrlen = 0;
315 	if ((hasqos = ieee80211_has_qos(wh))) {
316 		qos = ieee80211_get_qos(wh);
317 		tid = qos & IEEE80211_QOS_TID;
318 	} else {
319 		qos = 0;
320 		tid = 0;
321 	}
322 
323 	if (ic->ic_state == IEEE80211_S_RUN &&
324 	    type == IEEE80211_FC0_TYPE_DATA && hasqos &&
325 	    (subtype & IEEE80211_FC0_SUBTYPE_NODATA) == 0 &&
326 	    !(rxi->rxi_flags & IEEE80211_RXI_AMPDU_DONE)
327 #ifndef IEEE80211_STA_ONLY
328 	    && (ic->ic_opmode == IEEE80211_M_STA || ni != ic->ic_bss)
329 #endif
330 	    ) {
331 		int ba_state = ni->ni_rx_ba[tid].ba_state;
332 
333 #ifndef IEEE80211_STA_ONLY
334 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
335 			if (!IEEE80211_ADDR_EQ(wh->i_addr1,
336 			    ic->ic_bss->ni_bssid)) {
337 				ic->ic_stats.is_rx_wrongbss++;
338 				goto err;
339 			}
340 			if (ni->ni_state != IEEE80211_S_ASSOC) {
341 				ic->ic_stats.is_rx_notassoc++;
342 				goto err;
343 			}
344 		}
345 #endif
346 		/*
347 		 * If Block Ack was explicitly requested, check
348 		 * if we have a BA agreement for this RA/TID.
349 		 */
350 		if ((qos & IEEE80211_QOS_ACK_POLICY_MASK) ==
351 		    IEEE80211_QOS_ACK_POLICY_BA &&
352 		    ba_state != IEEE80211_BA_AGREED) {
353 			DPRINTF(("no BA agreement for %s, TID %d\n",
354 			    ether_sprintf(ni->ni_macaddr), tid));
355 			/* send a DELBA with reason code UNKNOWN-BA */
356 			IEEE80211_SEND_ACTION(ic, ni,
357 			    IEEE80211_CATEG_BA, IEEE80211_ACTION_DELBA,
358 			    IEEE80211_REASON_SETUP_REQUIRED << 16 | tid);
359 			goto err;
360 		}
361 
362 		/*
363 		 * Check if we have an explicit or implicit
364 		 * Block Ack Request for a valid BA agreement.
365 		 */
366 		if (ba_state == IEEE80211_BA_AGREED &&
367 		    ((qos & IEEE80211_QOS_ACK_POLICY_MASK) ==
368 		    IEEE80211_QOS_ACK_POLICY_BA ||
369 		    (qos & IEEE80211_QOS_ACK_POLICY_MASK) ==
370 		    IEEE80211_QOS_ACK_POLICY_NORMAL)) {
371 			/* go through A-MPDU reordering */
372 			ieee80211_input_ba(ic, m, ni, tid, rxi, ml);
373 			return;	/* don't free m! */
374 		} else if (ba_state == IEEE80211_BA_REQUESTED &&
375 		    (qos & IEEE80211_QOS_ACK_POLICY_MASK) ==
376 		    IEEE80211_QOS_ACK_POLICY_NORMAL) {
377 			/*
378 			 * Apparently, qos frames for a tid where a
379 			 * block ack agreement was requested but not
380 			 * yet confirmed by us should still contribute
381 			 * to the sequence number for this tid.
382 			 */
383 			ieee80211_input_ba(ic, m, ni, tid, rxi, ml);
384 			return;	/* don't free m! */
385 		}
386 	}
387 
388 	/*
389 	 * We do not yet support fragments. Drop any fragmented packets.
390 	 * Counter-measure against attacks where an arbitrary packet is
391 	 * injected via a fragment with attacker-controlled content.
392 	 * See https://papers.mathyvanhoef.com/usenix2021.pdf
393 	 * Section 6.8 "Treating fragments as full frames"
394 	 */
395 	if (ieee80211_has_seq(wh)) {
396 		uint16_t rxseq = letoh16(*(const u_int16_t *)wh->i_seq);
397 		if ((wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) ||
398 		    (rxseq & IEEE80211_SEQ_FRAG_MASK))
399 			goto err;
400 	}
401 
402 	/* duplicate detection (see 9.2.9) */
403 	if (ieee80211_has_seq(wh) &&
404 	    ic->ic_state != IEEE80211_S_SCAN) {
405 		nrxseq = letoh16(*(u_int16_t *)wh->i_seq) >>
406 		    IEEE80211_SEQ_SEQ_SHIFT;
407 		if (hasqos)
408 			orxseq = &ni->ni_qos_rxseqs[tid];
409 		else
410 			orxseq = &ni->ni_rxseq;
411 		if (rxi->rxi_flags & IEEE80211_RXI_SAME_SEQ) {
412 			if (nrxseq != *orxseq) {
413 				/* duplicate, silently discarded */
414 				ic->ic_stats.is_rx_dup++;
415 				goto out;
416 			}
417 		} else if ((wh->i_fc[1] & IEEE80211_FC1_RETRY) &&
418 		    nrxseq == *orxseq) {
419 			/* duplicate, silently discarded */
420 			ic->ic_stats.is_rx_dup++;
421 			goto out;
422 		}
423 		*orxseq = nrxseq;
424 	}
425 	if (ic->ic_state > IEEE80211_S_SCAN) {
426 		ni->ni_rssi = rxi->rxi_rssi;
427 		ni->ni_rstamp = rxi->rxi_tstamp;
428 		ni->ni_inact = 0;
429 
430 		if (ic->ic_state == IEEE80211_S_RUN && ic->ic_bgscan_start) {
431 			/* Cancel or start background scan based on RSSI. */
432 			if ((*ic->ic_node_checkrssi)(ic, ni))
433 				timeout_del(&ic->ic_bgscan_timeout);
434 			else if (!timeout_pending(&ic->ic_bgscan_timeout) &&
435 			    (ic->ic_flags & IEEE80211_F_BGSCAN) == 0 &&
436 			    (ic->ic_flags & IEEE80211_F_DESBSSID) == 0)
437 				timeout_add_msec(&ic->ic_bgscan_timeout,
438 				    500 * (ic->ic_bgscan_fail + 1));
439 		}
440 	}
441 
442 #ifndef IEEE80211_STA_ONLY
443 	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
444 	    (ic->ic_caps & IEEE80211_C_APPMGT) &&
445 	    ni->ni_state == IEEE80211_STA_ASSOC) {
446 		if (wh->i_fc[1] & IEEE80211_FC1_PWR_MGT) {
447 			if (ni->ni_pwrsave == IEEE80211_PS_AWAKE) {
448 				/* turn on PS mode */
449 				ni->ni_pwrsave = IEEE80211_PS_DOZE;
450 				DPRINTF(("PS mode on for %s\n",
451 				    ether_sprintf(wh->i_addr2)));
452 			}
453 		} else if (ni->ni_pwrsave == IEEE80211_PS_DOZE) {
454 			struct mbuf *m;
455 
456 			/* turn off PS mode */
457 			ni->ni_pwrsave = IEEE80211_PS_AWAKE;
458 			DPRINTF(("PS mode off for %s\n",
459 			    ether_sprintf(wh->i_addr2)));
460 
461 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
462 
463 			/* dequeue buffered unicast frames */
464 			while ((m = mq_dequeue(&ni->ni_savedq)) != NULL) {
465 				mq_enqueue(&ic->ic_pwrsaveq, m);
466 				if_start(ifp);
467 			}
468 		}
469 	}
470 #endif
471 	switch (type) {
472 	case IEEE80211_FC0_TYPE_DATA:
473 		switch (ic->ic_opmode) {
474 		case IEEE80211_M_STA:
475 			if (dir != IEEE80211_FC1_DIR_FROMDS) {
476 				ic->ic_stats.is_rx_wrongdir++;
477 				goto out;
478 			}
479 			if (ic->ic_state != IEEE80211_S_SCAN &&
480 			    !IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_bssid)) {
481 				/* Source address is not our BSS. */
482 				DPRINTF(("discard frame from SA %s\n",
483 				    ether_sprintf(wh->i_addr2)));
484 				ic->ic_stats.is_rx_wrongbss++;
485 				goto out;
486 			}
487 			if ((ifp->if_flags & IFF_SIMPLEX) &&
488 			    IEEE80211_IS_MULTICAST(wh->i_addr1) &&
489 			    IEEE80211_ADDR_EQ(wh->i_addr3, ic->ic_myaddr)) {
490 				/*
491 				 * In IEEE802.11 network, multicast frame
492 				 * sent from me is broadcasted from AP.
493 				 * It should be silently discarded for
494 				 * SIMPLEX interface.
495 				 */
496 				ic->ic_stats.is_rx_mcastecho++;
497 				goto out;
498 			}
499 			break;
500 #ifndef IEEE80211_STA_ONLY
501 		case IEEE80211_M_IBSS:
502 		case IEEE80211_M_AHDEMO:
503 			if (dir != IEEE80211_FC1_DIR_NODS) {
504 				ic->ic_stats.is_rx_wrongdir++;
505 				goto out;
506 			}
507 			if (ic->ic_state != IEEE80211_S_SCAN &&
508 			    !IEEE80211_ADDR_EQ(wh->i_addr3,
509 				ic->ic_bss->ni_bssid) &&
510 			    !IEEE80211_ADDR_EQ(wh->i_addr3,
511 				etherbroadcastaddr)) {
512 				/* Destination is not our BSS or broadcast. */
513 				DPRINTF(("discard data frame to DA %s\n",
514 				    ether_sprintf(wh->i_addr3)));
515 				ic->ic_stats.is_rx_wrongbss++;
516 				goto out;
517 			}
518 			break;
519 		case IEEE80211_M_HOSTAP:
520 			if (dir != IEEE80211_FC1_DIR_TODS) {
521 				ic->ic_stats.is_rx_wrongdir++;
522 				goto out;
523 			}
524 			if (ic->ic_state != IEEE80211_S_SCAN &&
525 			    !IEEE80211_ADDR_EQ(wh->i_addr1,
526 				ic->ic_bss->ni_bssid) &&
527 			    !IEEE80211_ADDR_EQ(wh->i_addr1,
528 				etherbroadcastaddr)) {
529 				/* BSS is not us or broadcast. */
530 				DPRINTF(("discard data frame to BSS %s\n",
531 				    ether_sprintf(wh->i_addr1)));
532 				ic->ic_stats.is_rx_wrongbss++;
533 				goto out;
534 			}
535 			/* check if source STA is associated */
536 			if (ni == ic->ic_bss) {
537 				DPRINTF(("data from unknown src %s\n",
538 				    ether_sprintf(wh->i_addr2)));
539 				/* NB: caller deals with reference */
540 				ni = ieee80211_find_node(ic, wh->i_addr2);
541 				if (ni == NULL)
542 					ni = ieee80211_dup_bss(ic, wh->i_addr2);
543 				if (ni != NULL) {
544 					IEEE80211_SEND_MGMT(ic, ni,
545 					    IEEE80211_FC0_SUBTYPE_DEAUTH,
546 					    IEEE80211_REASON_NOT_AUTHED);
547 				}
548 				ic->ic_stats.is_rx_notassoc++;
549 				goto err;
550 			}
551 			if (ni->ni_state != IEEE80211_STA_ASSOC) {
552 				DPRINTF(("data from unassoc src %s\n",
553 				    ether_sprintf(wh->i_addr2)));
554 				IEEE80211_SEND_MGMT(ic, ni,
555 				    IEEE80211_FC0_SUBTYPE_DISASSOC,
556 				    IEEE80211_REASON_NOT_ASSOCED);
557 				ic->ic_stats.is_rx_notassoc++;
558 				goto err;
559 			}
560 			break;
561 #endif	/* IEEE80211_STA_ONLY */
562 		default:
563 			/* can't get there */
564 			goto out;
565 		}
566 
567 		/* Do not process "no data" frames any further. */
568 		if (subtype & IEEE80211_FC0_SUBTYPE_NODATA) {
569 #if NBPFILTER > 0
570 			if (ic->ic_rawbpf)
571 				bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_IN);
572 #endif
573 			goto out;
574 		}
575 
576 		if ((ic->ic_flags & IEEE80211_F_WEPON) ||
577 		    ((ic->ic_flags & IEEE80211_F_RSNON) &&
578 		     (ni->ni_flags & IEEE80211_NODE_RXPROT))) {
579 			/* protection is on for Rx */
580 			if (!(rxi->rxi_flags & IEEE80211_RXI_HWDEC)) {
581 				if (!(wh->i_fc[1] & IEEE80211_FC1_PROTECTED)) {
582 					/* drop unencrypted */
583 					ic->ic_stats.is_rx_unencrypted++;
584 					goto err;
585 				}
586 				/* do software decryption */
587 				m = ieee80211_decrypt(ic, m, ni);
588 				if (m == NULL) {
589 					ic->ic_stats.is_rx_wepfail++;
590 					goto err;
591 				}
592 			} else {
593 				m = ieee80211_input_hwdecrypt(ic, ni, m, rxi);
594 				if (m == NULL)
595 					goto err;
596 			}
597 			wh = mtod(m, struct ieee80211_frame *);
598 		} else if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) ||
599 		    (rxi->rxi_flags & IEEE80211_RXI_HWDEC)) {
600 			/* frame encrypted but protection off for Rx */
601 			ic->ic_stats.is_rx_nowep++;
602 			goto out;
603 		}
604 
605 #if NBPFILTER > 0
606 		/* copy to listener after decrypt */
607 		if (ic->ic_rawbpf)
608 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_IN);
609 #endif
610 
611 		if ((ni->ni_flags & IEEE80211_NODE_HT) &&
612 		    hasqos && (qos & IEEE80211_QOS_AMSDU))
613 			ieee80211_amsdu_decap(ic, m, ni, hdrlen, ml);
614 		else
615 			ieee80211_decap(ic, m, ni, hdrlen, ml);
616 		return;
617 
618 	case IEEE80211_FC0_TYPE_MGT:
619 		if (dir != IEEE80211_FC1_DIR_NODS) {
620 			ic->ic_stats.is_rx_wrongdir++;
621 			goto err;
622 		}
623 #ifndef IEEE80211_STA_ONLY
624 		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
625 			ic->ic_stats.is_rx_ahdemo_mgt++;
626 			goto out;
627 		}
628 #endif
629 		/* drop frames without interest */
630 		if (ic->ic_state == IEEE80211_S_SCAN) {
631 			if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
632 			    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
633 				ic->ic_stats.is_rx_mgtdiscard++;
634 				goto out;
635 			}
636 		}
637 
638 		if (ni->ni_flags & IEEE80211_NODE_RXMGMTPROT) {
639 			/* MMPDU protection is on for Rx */
640 			if (subtype == IEEE80211_FC0_SUBTYPE_DISASSOC ||
641 			    subtype == IEEE80211_FC0_SUBTYPE_DEAUTH ||
642 			    subtype == IEEE80211_FC0_SUBTYPE_ACTION) {
643 				if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
644 				    !(wh->i_fc[1] & IEEE80211_FC1_PROTECTED)) {
645 					/* unicast mgmt not encrypted */
646 					goto out;
647 				}
648 				/* do software decryption */
649 				m = ieee80211_decrypt(ic, m, ni);
650 				if (m == NULL) {
651 					/* XXX stats */
652 					goto out;
653 				}
654 				wh = mtod(m, struct ieee80211_frame *);
655 			}
656 		} else if ((ic->ic_flags & IEEE80211_F_RSNON) &&
657 		    (wh->i_fc[1] & IEEE80211_FC1_PROTECTED)) {
658 			/* encrypted but MMPDU Rx protection off for TA */
659 			goto out;
660 		}
661 
662 #if NBPFILTER > 0
663 		if (bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_IN) != 0) {
664 			/*
665 			 * Drop mbuf if it was filtered by bpf. Normally,
666 			 * this is done in ether_input() but IEEE 802.11
667 			 * management frames are a special case.
668 			 */
669 			m_freem(m);
670 			return;
671 		}
672 #endif
673 		(*ic->ic_recv_mgmt)(ic, m, ni, rxi, subtype);
674 		m_freem(m);
675 		return;
676 
677 	case IEEE80211_FC0_TYPE_CTL:
678 		switch (subtype) {
679 #ifndef IEEE80211_STA_ONLY
680 		case IEEE80211_FC0_SUBTYPE_PS_POLL:
681 			ieee80211_recv_pspoll(ic, m, ni);
682 			break;
683 #endif
684 		case IEEE80211_FC0_SUBTYPE_BAR:
685 			ieee80211_recv_bar(ic, m, ni);
686 			break;
687 		default:
688 			ic->ic_stats.is_rx_ctl++;
689 			break;
690 		}
691 		goto out;
692 
693 	default:
694 		DPRINTF(("bad frame type %x\n", type));
695 		/* should not come here */
696 		break;
697 	}
698  err:
699 	ifp->if_ierrors++;
700  out:
701 	if (m != NULL) {
702 #if NBPFILTER > 0
703 		if (ic->ic_rawbpf)
704 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_IN);
705 #endif
706 		m_freem(m);
707 	}
708 }
709 
710 /* Input handler for drivers which only receive one frame per interrupt. */
711 void
712 ieee80211_input(struct ifnet *ifp, struct mbuf *m, struct ieee80211_node *ni,
713     struct ieee80211_rxinfo *rxi)
714 {
715 	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
716 
717 	ieee80211_inputm(ifp, m, ni, rxi, &ml);
718 	if_input(ifp, &ml);
719 }
720 
721 #ifdef notyet
722 /*
723  * Handle defragmentation (see 9.5 and Annex C).  We support the concurrent
724  * reception of fragments of three fragmented MSDUs or MMPDUs.
725  */
726 struct mbuf *
727 ieee80211_defrag(struct ieee80211com *ic, struct mbuf *m, int hdrlen)
728 {
729 	const struct ieee80211_frame *owh, *wh;
730 	struct ieee80211_defrag *df;
731 	u_int16_t rxseq, seq;
732 	u_int8_t frag;
733 	int i;
734 
735 	wh = mtod(m, struct ieee80211_frame *);
736 	rxseq = letoh16(*(const u_int16_t *)wh->i_seq);
737 	seq = rxseq >> IEEE80211_SEQ_SEQ_SHIFT;
738 	frag = rxseq & IEEE80211_SEQ_FRAG_MASK;
739 
740 	if (frag == 0 && !(wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG))
741 		return m;	/* not fragmented */
742 
743 	if (frag == 0) {
744 		/* first fragment, setup entry in the fragment cache */
745 		if (++ic->ic_defrag_cur == IEEE80211_DEFRAG_SIZE)
746 			ic->ic_defrag_cur = 0;
747 		df = &ic->ic_defrag[ic->ic_defrag_cur];
748 		m_freem(df->df_m);	/* discard old entry */
749 		df->df_seq = seq;
750 		df->df_frag = 0;
751 		df->df_m = m;
752 		/* start receive MSDU timer of aMaxReceiveLifetime */
753 		timeout_add_sec(&df->df_to, 1);
754 		return NULL;	/* MSDU or MMPDU not yet complete */
755 	}
756 
757 	/* find matching entry in the fragment cache */
758 	for (i = 0; i < IEEE80211_DEFRAG_SIZE; i++) {
759 		df = &ic->ic_defrag[i];
760 		if (df->df_m == NULL)
761 			continue;
762 		if (df->df_seq != seq || df->df_frag + 1 != frag)
763 			continue;
764 		owh = mtod(df->df_m, struct ieee80211_frame *);
765 		/* frame type, source and destination must match */
766 		if (((wh->i_fc[0] ^ owh->i_fc[0]) & IEEE80211_FC0_TYPE_MASK) ||
767 		    !IEEE80211_ADDR_EQ(wh->i_addr1, owh->i_addr1) ||
768 		    !IEEE80211_ADDR_EQ(wh->i_addr2, owh->i_addr2))
769 			continue;
770 		/* matching entry found */
771 		break;
772 	}
773 	if (i == IEEE80211_DEFRAG_SIZE) {
774 		/* no matching entry found, discard fragment */
775 		ic->ic_if.if_ierrors++;
776 		m_freem(m);
777 		return NULL;
778 	}
779 
780 	df->df_frag = frag;
781 	/* strip 802.11 header and concatenate fragment */
782 	m_adj(m, hdrlen);
783 	m_cat(df->df_m, m);
784 	df->df_m->m_pkthdr.len += m->m_pkthdr.len;
785 
786 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
787 		return NULL;	/* MSDU or MMPDU not yet complete */
788 
789 	/* MSDU or MMPDU complete */
790 	timeout_del(&df->df_to);
791 	m = df->df_m;
792 	df->df_m = NULL;
793 	return m;
794 }
795 
796 /*
797  * Receive MSDU defragmentation timer exceeds aMaxReceiveLifetime.
798  */
799 void
800 ieee80211_defrag_timeout(void *arg)
801 {
802 	struct ieee80211_defrag *df = arg;
803 	int s = splnet();
804 
805 	/* discard all received fragments */
806 	m_freem(df->df_m);
807 	df->df_m = NULL;
808 
809 	splx(s);
810 }
811 #endif
812 
813 /*
814  * Process a received data MPDU related to a specific HT-immediate Block Ack
815  * agreement (see 9.10.7.6).
816  */
817 void
818 ieee80211_input_ba(struct ieee80211com *ic, struct mbuf *m,
819     struct ieee80211_node *ni, int tid, struct ieee80211_rxinfo *rxi,
820     struct mbuf_list *ml)
821 {
822 	struct ifnet *ifp = &ic->ic_if;
823 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
824 	struct ieee80211_frame *wh;
825 	int idx, count;
826 	u_int16_t sn;
827 
828 	wh = mtod(m, struct ieee80211_frame *);
829 	sn = letoh16(*(u_int16_t *)wh->i_seq) >> IEEE80211_SEQ_SEQ_SHIFT;
830 
831 	/* reset Block Ack inactivity timer */
832 	if (ba->ba_timeout_val != 0)
833 		timeout_add_usec(&ba->ba_to, ba->ba_timeout_val);
834 
835 	if (SEQ_LT(sn, ba->ba_winstart)) {	/* SN < WinStartB */
836 		ic->ic_stats.is_ht_rx_frame_below_ba_winstart++;
837 		m_freem(m);	/* discard the MPDU */
838 		return;
839 	}
840 	if (SEQ_LT(ba->ba_winend, sn)) {	/* WinEndB < SN */
841 		ic->ic_stats.is_ht_rx_frame_above_ba_winend++;
842 		count = (sn - ba->ba_winend) & 0xfff;
843 		if (count > ba->ba_winsize) {
844 			/*
845 			 * Check whether we're consistently behind the window,
846 			 * and let the window move forward if necessary.
847 			 */
848 			if (ba->ba_winmiss < IEEE80211_BA_MAX_WINMISS) {
849 				if (ba->ba_missedsn == ((sn - 1) & 0xfff))
850 					ba->ba_winmiss++;
851 				else
852 					ba->ba_winmiss = 0;
853 				ba->ba_missedsn = sn;
854 				ifp->if_ierrors++;
855 				m_freem(m);	/* discard the MPDU */
856 				return;
857 			}
858 
859 			/* It appears the window has moved for real. */
860 			ic->ic_stats.is_ht_rx_ba_window_jump++;
861 			ba->ba_winmiss = 0;
862 			ba->ba_missedsn = 0;
863 			ieee80211_ba_move_window(ic, ni, tid, sn, ml);
864 		} else {
865 			ic->ic_stats.is_ht_rx_ba_window_slide++;
866 			ieee80211_input_ba_seq(ic, ni, tid,
867 			    (ba->ba_winstart + count) & 0xfff, ml);
868 			ieee80211_input_ba_flush(ic, ni, ba, ml);
869 		}
870 	}
871 	/* WinStartB <= SN <= WinEndB */
872 
873 	ba->ba_winmiss = 0;
874 	ba->ba_missedsn = 0;
875 	idx = (sn - ba->ba_winstart) & 0xfff;
876 	idx = (ba->ba_head + idx) % IEEE80211_BA_MAX_WINSZ;
877 	/* store the received MPDU in the buffer */
878 	if (ba->ba_buf[idx].m != NULL) {
879 		ifp->if_ierrors++;
880 		ic->ic_stats.is_ht_rx_ba_no_buf++;
881 		m_freem(m);
882 		return;
883 	}
884 	ba->ba_buf[idx].m = m;
885 	/* store Rx meta-data too */
886 	rxi->rxi_flags |= IEEE80211_RXI_AMPDU_DONE;
887 	ba->ba_buf[idx].rxi = *rxi;
888 	ba->ba_gapwait++;
889 
890 	if (ba->ba_buf[ba->ba_head].m == NULL && ba->ba_gapwait == 1)
891 		timeout_add_msec(&ba->ba_gap_to, IEEE80211_BA_GAP_TIMEOUT);
892 
893 	ieee80211_input_ba_flush(ic, ni, ba, ml);
894 }
895 
896 /*
897  * Forward buffered frames with sequence number lower than max_seq.
898  * See 802.11-2012 9.21.7.6.2 b.
899  */
900 void
901 ieee80211_input_ba_seq(struct ieee80211com *ic, struct ieee80211_node *ni,
902     uint8_t tid, uint16_t max_seq, struct mbuf_list *ml)
903 {
904 	struct ifnet *ifp = &ic->ic_if;
905 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
906 	struct ieee80211_frame *wh;
907 	uint16_t seq;
908 	int i = 0;
909 
910 	while (i++ < ba->ba_winsize) {
911 		/* gaps may exist */
912 		if (ba->ba_buf[ba->ba_head].m != NULL) {
913 			wh = mtod(ba->ba_buf[ba->ba_head].m,
914 			    struct ieee80211_frame *);
915 			KASSERT(ieee80211_has_seq(wh));
916 			seq = letoh16(*(u_int16_t *)wh->i_seq) >>
917 			    IEEE80211_SEQ_SEQ_SHIFT;
918 			if (!SEQ_LT(seq, max_seq))
919 				break;
920 			ieee80211_inputm(ifp, ba->ba_buf[ba->ba_head].m,
921 			    ni, &ba->ba_buf[ba->ba_head].rxi, ml);
922 			ba->ba_buf[ba->ba_head].m = NULL;
923 			ba->ba_gapwait--;
924 		} else
925 			ic->ic_stats.is_ht_rx_ba_frame_lost++;
926 		ba->ba_head = (ba->ba_head + 1) % IEEE80211_BA_MAX_WINSZ;
927 		/* move window forward */
928 		ba->ba_winstart = (ba->ba_winstart + 1) & 0xfff;
929 	}
930 	ba->ba_winend = (ba->ba_winstart + ba->ba_winsize - 1) & 0xfff;
931 }
932 
933 /* Flush a consecutive sequence of frames from the reorder buffer. */
934 void
935 ieee80211_input_ba_flush(struct ieee80211com *ic, struct ieee80211_node *ni,
936     struct ieee80211_rx_ba *ba, struct mbuf_list *ml)
937 
938 {
939 	struct ifnet *ifp = &ic->ic_if;
940 
941 	/* Do not re-arm the gap timeout if we made no progress. */
942 	if (ba->ba_buf[ba->ba_head].m == NULL)
943 		return;
944 
945 	/* pass reordered MPDUs up to the next MAC process */
946 	while (ba->ba_buf[ba->ba_head].m != NULL) {
947 		ieee80211_inputm(ifp, ba->ba_buf[ba->ba_head].m, ni,
948 		    &ba->ba_buf[ba->ba_head].rxi, ml);
949 		ba->ba_buf[ba->ba_head].m = NULL;
950 		ba->ba_gapwait--;
951 
952 		ba->ba_head = (ba->ba_head + 1) % IEEE80211_BA_MAX_WINSZ;
953 		/* move window forward */
954 		ba->ba_winstart = (ba->ba_winstart + 1) & 0xfff;
955 	}
956 	ba->ba_winend = (ba->ba_winstart + ba->ba_winsize - 1) & 0xfff;
957 
958 	if (timeout_pending(&ba->ba_gap_to))
959 		timeout_del(&ba->ba_gap_to);
960 	if (ba->ba_gapwait)
961 		timeout_add_msec(&ba->ba_gap_to, IEEE80211_BA_GAP_TIMEOUT);
962 }
963 
964 /*
965  * Forcibly move the BA window forward to remove a leading gap which has
966  * been causing frames to linger in the reordering buffer for too long.
967  * A leading gap will occur if a particular A-MPDU subframe never arrives
968  * or if a bug in the sender causes sequence numbers to jump forward by > 1.
969  */
970 int
971 ieee80211_input_ba_gap_skip(struct ieee80211_rx_ba *ba)
972 {
973 	int skipped = 0;
974 
975 	while (skipped < ba->ba_winsize && ba->ba_buf[ba->ba_head].m == NULL) {
976 		/* move window forward */
977 		ba->ba_head = (ba->ba_head + 1) % IEEE80211_BA_MAX_WINSZ;
978 		ba->ba_winstart = (ba->ba_winstart + 1) & 0xfff;
979 		skipped++;
980 	}
981 	if (skipped > 0)
982 		ba->ba_winend = (ba->ba_winstart + ba->ba_winsize - 1) & 0xfff;
983 
984 	return skipped;
985 }
986 
987 void
988 ieee80211_input_ba_gap_timeout(void *arg)
989 {
990 	struct ieee80211_rx_ba *ba = arg;
991 	struct ieee80211_node *ni = ba->ba_ni;
992 	struct ieee80211com *ic = ni->ni_ic;
993 	int s, skipped;
994 
995 	ic->ic_stats.is_ht_rx_ba_window_gap_timeout++;
996 
997 	s = splnet();
998 
999 	skipped = ieee80211_input_ba_gap_skip(ba);
1000 	ic->ic_stats.is_ht_rx_ba_frame_lost += skipped;
1001 	if (skipped) {
1002 		struct mbuf_list ml = MBUF_LIST_INITIALIZER();
1003 		ieee80211_input_ba_flush(ic, ni, ba, &ml);
1004 		if_input(&ic->ic_if, &ml);
1005 	}
1006 
1007 	splx(s);
1008 }
1009 
1010 
1011 /*
1012  * Change the value of WinStartB (move window forward) upon reception of a
1013  * BlockAckReq frame or an ADDBA Request (PBAC).
1014  */
1015 void
1016 ieee80211_ba_move_window(struct ieee80211com *ic, struct ieee80211_node *ni,
1017     u_int8_t tid, u_int16_t ssn, struct mbuf_list *ml)
1018 {
1019 	struct ifnet *ifp = &ic->ic_if;
1020 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
1021 	int count;
1022 
1023 	/* assert(WinStartB <= SSN) */
1024 
1025 	count = (ssn - ba->ba_winstart) & 0xfff;
1026 	if (count > ba->ba_winsize)	/* no overlap */
1027 		count = ba->ba_winsize;
1028 	while (count-- > 0) {
1029 		/* gaps may exist */
1030 		if (ba->ba_buf[ba->ba_head].m != NULL) {
1031 			ieee80211_inputm(ifp, ba->ba_buf[ba->ba_head].m, ni,
1032 			    &ba->ba_buf[ba->ba_head].rxi, ml);
1033 			ba->ba_buf[ba->ba_head].m = NULL;
1034 			ba->ba_gapwait--;
1035 		} else
1036 			ic->ic_stats.is_ht_rx_ba_frame_lost++;
1037 		ba->ba_head = (ba->ba_head + 1) % IEEE80211_BA_MAX_WINSZ;
1038 	}
1039 	/* move window forward */
1040 	ba->ba_winstart = ssn;
1041 	ba->ba_winend = (ba->ba_winstart + ba->ba_winsize - 1) & 0xfff;
1042 
1043 	ieee80211_input_ba_flush(ic, ni, ba, ml);
1044 }
1045 
1046 void
1047 ieee80211_enqueue_data(struct ieee80211com *ic, struct mbuf *m,
1048     struct ieee80211_node *ni, int mcast, struct mbuf_list *ml)
1049 {
1050 	struct ifnet *ifp = &ic->ic_if;
1051 	struct ether_header *eh;
1052 	struct mbuf *m1;
1053 
1054 	eh = mtod(m, struct ether_header *);
1055 
1056 	if ((ic->ic_flags & IEEE80211_F_RSNON) && !ni->ni_port_valid &&
1057 	    eh->ether_type != htons(ETHERTYPE_EAPOL)) {
1058 		DPRINTF(("port not valid: %s\n",
1059 		    ether_sprintf(eh->ether_dhost)));
1060 		ic->ic_stats.is_rx_unauth++;
1061 		m_freem(m);
1062 		return;
1063 	}
1064 
1065 	/*
1066 	 * Perform as a bridge within the AP.  Notice that we do not
1067 	 * bridge EAPOL frames as suggested in C.1.1 of IEEE Std 802.1X.
1068 	 * And we do not forward unicast frames received on a multicast address.
1069 	 */
1070 	m1 = NULL;
1071 #ifndef IEEE80211_STA_ONLY
1072 	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1073 	    !(ic->ic_userflags & IEEE80211_F_NOBRIDGE) &&
1074 	    eh->ether_type != htons(ETHERTYPE_EAPOL)) {
1075 		struct ieee80211_node *ni1;
1076 
1077 		if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
1078 			m1 = m_dup_pkt(m, ETHER_ALIGN, M_DONTWAIT);
1079 			if (m1 == NULL)
1080 				ifp->if_oerrors++;
1081 			else
1082 				m1->m_flags |= M_MCAST;
1083 		} else if (!mcast) {
1084 			ni1 = ieee80211_find_node(ic, eh->ether_dhost);
1085 			if (ni1 != NULL &&
1086 			    ni1->ni_state == IEEE80211_STA_ASSOC) {
1087 				m1 = m;
1088 				m = NULL;
1089 			}
1090 		}
1091 		if (m1 != NULL) {
1092 			if (if_enqueue(ifp, m1))
1093 				 ifp->if_oerrors++;
1094 		}
1095 	}
1096 #endif
1097 	if (m != NULL) {
1098 		if ((ic->ic_flags & IEEE80211_F_RSNON) &&
1099 		    eh->ether_type == htons(ETHERTYPE_EAPOL)) {
1100 			ifp->if_ipackets++;
1101 #if NBPFILTER > 0
1102 			/*
1103 			 * If we forward frame into transmitter of the AP,
1104 			 * we don't need to duplicate for DLT_EN10MB.
1105 			 */
1106 			if (ifp->if_bpf && m1 == NULL)
1107 				bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_IN);
1108 #endif
1109 			ieee80211_eapol_key_input(ic, m, ni);
1110 		} else {
1111 			ml_enqueue(ml, m);
1112 		}
1113 	}
1114 }
1115 
1116 void
1117 ieee80211_decap(struct ieee80211com *ic, struct mbuf *m,
1118     struct ieee80211_node *ni, int hdrlen, struct mbuf_list *ml)
1119 {
1120 	struct ether_header eh;
1121 	struct ieee80211_frame *wh;
1122 	struct llc *llc;
1123 	int mcast;
1124 
1125 	if (m->m_len < hdrlen + LLC_SNAPFRAMELEN &&
1126 	    (m = m_pullup(m, hdrlen + LLC_SNAPFRAMELEN)) == NULL) {
1127 		ic->ic_stats.is_rx_decap++;
1128 		return;
1129 	}
1130 	wh = mtod(m, struct ieee80211_frame *);
1131 	mcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1132 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
1133 	case IEEE80211_FC1_DIR_NODS:
1134 		IEEE80211_ADDR_COPY(eh.ether_dhost, wh->i_addr1);
1135 		IEEE80211_ADDR_COPY(eh.ether_shost, wh->i_addr2);
1136 		break;
1137 	case IEEE80211_FC1_DIR_TODS:
1138 		IEEE80211_ADDR_COPY(eh.ether_dhost, wh->i_addr3);
1139 		IEEE80211_ADDR_COPY(eh.ether_shost, wh->i_addr2);
1140 		break;
1141 	case IEEE80211_FC1_DIR_FROMDS:
1142 		IEEE80211_ADDR_COPY(eh.ether_dhost, wh->i_addr1);
1143 		IEEE80211_ADDR_COPY(eh.ether_shost, wh->i_addr3);
1144 		break;
1145 	case IEEE80211_FC1_DIR_DSTODS:
1146 		IEEE80211_ADDR_COPY(eh.ether_dhost, wh->i_addr3);
1147 		IEEE80211_ADDR_COPY(eh.ether_shost,
1148 		    ((struct ieee80211_frame_addr4 *)wh)->i_addr4);
1149 		break;
1150 	}
1151 	llc = (struct llc *)((caddr_t)wh + hdrlen);
1152 	if (llc->llc_dsap == LLC_SNAP_LSAP &&
1153 	    llc->llc_ssap == LLC_SNAP_LSAP &&
1154 	    llc->llc_control == LLC_UI &&
1155 	    llc->llc_snap.org_code[0] == 0 &&
1156 	    llc->llc_snap.org_code[1] == 0 &&
1157 	    llc->llc_snap.org_code[2] == 0) {
1158 		eh.ether_type = llc->llc_snap.ether_type;
1159 		m_adj(m, hdrlen + LLC_SNAPFRAMELEN - ETHER_HDR_LEN);
1160 	} else {
1161 		eh.ether_type = htons(m->m_pkthdr.len - hdrlen);
1162 		m_adj(m, hdrlen - ETHER_HDR_LEN);
1163 	}
1164 	memcpy(mtod(m, caddr_t), &eh, ETHER_HDR_LEN);
1165 	if (!ALIGNED_POINTER(mtod(m, caddr_t) + ETHER_HDR_LEN, u_int32_t)) {
1166 		struct mbuf *m0 = m;
1167 		m = m_dup_pkt(m0, ETHER_ALIGN, M_NOWAIT);
1168 		m_freem(m0);
1169 		if (m == NULL) {
1170 			ic->ic_stats.is_rx_decap++;
1171 			return;
1172 		}
1173 	}
1174 	ieee80211_enqueue_data(ic, m, ni, mcast, ml);
1175 }
1176 
1177 int
1178 ieee80211_amsdu_decap_validate(struct ieee80211com *ic, struct mbuf *m,
1179     struct ieee80211_node *ni)
1180 {
1181 	struct ether_header *eh = mtod(m, struct ether_header *);
1182 	const uint8_t llc_hdr_mac[ETHER_ADDR_LEN] = {
1183 		/* MAC address matching the 802.2 LLC header. */
1184 		LLC_SNAP_LSAP, LLC_SNAP_LSAP, LLC_UI, 0, 0, 0
1185 	};
1186 
1187 	/*
1188 	 * We are sorry, but this particular MAC address cannot be used.
1189 	 * This mitigates an attack where a single 802.11 frame is interpreted
1190 	 * as an A-MSDU because of a forged AMSDU-present bit in the 802.11
1191 	 * QoS frame header: https://papers.mathyvanhoef.com/usenix2021.pdf
1192 	 * See Section 7.2, 'Countermeasures for the design flaws'
1193 	 */
1194 	if (ETHER_IS_EQ(eh->ether_dhost, llc_hdr_mac))
1195 		return 1;
1196 
1197 	switch (ic->ic_opmode) {
1198 #ifndef IEEE80211_STA_ONLY
1199 	case IEEE80211_M_HOSTAP:
1200 		/*
1201 		 * Subframes must use the source address of the node which
1202 		 * transmitted the A-MSDU. Prevents MAC spoofing.
1203 		 */
1204 		if (!ETHER_IS_EQ(ni->ni_macaddr, eh->ether_shost))
1205 			return 1;
1206 		break;
1207 #endif
1208 	case IEEE80211_M_STA:
1209 		/* Subframes must be addressed to me. */
1210 		if (!ETHER_IS_EQ(ic->ic_myaddr, eh->ether_dhost))
1211 			return 1;
1212 		break;
1213 	default:
1214 		/* Ignore MONITOR/IBSS modes for now. */
1215 		break;
1216 	}
1217 
1218 	return 0;
1219 }
1220 
1221 /*
1222  * Decapsulate an Aggregate MSDU (see 7.2.2.2).
1223  */
1224 void
1225 ieee80211_amsdu_decap(struct ieee80211com *ic, struct mbuf *m,
1226     struct ieee80211_node *ni, int hdrlen, struct mbuf_list *ml)
1227 {
1228 	struct mbuf *n;
1229 	struct ether_header *eh;
1230 	struct llc *llc;
1231 	int len, pad, mcast;
1232 	struct ieee80211_frame *wh;
1233 	struct mbuf_list subframes = MBUF_LIST_INITIALIZER();
1234 
1235 	wh = mtod(m, struct ieee80211_frame *);
1236 	mcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1237 
1238 	/* strip 802.11 header */
1239 	m_adj(m, hdrlen);
1240 
1241 	while (m->m_pkthdr.len >= ETHER_HDR_LEN + LLC_SNAPFRAMELEN) {
1242 		/* process an A-MSDU subframe */
1243 		m = m_pullup(m, ETHER_HDR_LEN + LLC_SNAPFRAMELEN);
1244 		if (m == NULL)
1245 			break;
1246 		eh = mtod(m, struct ether_header *);
1247 		/* examine 802.3 header */
1248 		len = ntohs(eh->ether_type);
1249 		if (len < LLC_SNAPFRAMELEN) {
1250 			DPRINTF(("A-MSDU subframe too short (%d)\n", len));
1251 			/* stop processing A-MSDU subframes */
1252 			ic->ic_stats.is_rx_decap++;
1253 			ml_purge(&subframes);
1254 			m_freem(m);
1255 			return;
1256 		}
1257 		llc = (struct llc *)&eh[1];
1258 		/* Examine the 802.2 LLC header after the A-MSDU header. */
1259 		if (llc->llc_dsap == LLC_SNAP_LSAP &&
1260 		    llc->llc_ssap == LLC_SNAP_LSAP &&
1261 		    llc->llc_control == LLC_UI &&
1262 		    llc->llc_snap.org_code[0] == 0 &&
1263 		    llc->llc_snap.org_code[1] == 0 &&
1264 		    llc->llc_snap.org_code[2] == 0) {
1265 			/* convert to Ethernet II header */
1266 			eh->ether_type = llc->llc_snap.ether_type;
1267 			/* strip LLC+SNAP headers */
1268 			memmove((u_int8_t *)eh + LLC_SNAPFRAMELEN, eh,
1269 			    ETHER_HDR_LEN);
1270 			m_adj(m, LLC_SNAPFRAMELEN);
1271 			len -= LLC_SNAPFRAMELEN;
1272 		}
1273 		len += ETHER_HDR_LEN;
1274 		if (len > m->m_pkthdr.len) {
1275 			/* stop processing A-MSDU subframes */
1276 			DPRINTF(("A-MSDU subframe too long (%d)\n", len));
1277 			ic->ic_stats.is_rx_decap++;
1278 			ml_purge(&subframes);
1279 			m_freem(m);
1280 			return;
1281 		}
1282 
1283 		/* "detach" our A-MSDU subframe from the others */
1284 		n = m_split(m, len, M_NOWAIT);
1285 		if (n == NULL) {
1286 			/* stop processing A-MSDU subframes */
1287 			ic->ic_stats.is_rx_decap++;
1288 			ml_purge(&subframes);
1289 			m_freem(m);
1290 			return;
1291 		}
1292 
1293 		if (ieee80211_amsdu_decap_validate(ic, m, ni)) {
1294 			/* stop processing A-MSDU subframes */
1295 			ic->ic_stats.is_rx_decap++;
1296 			ml_purge(&subframes);
1297 			m_freem(m);
1298 			return;
1299 		}
1300 
1301 		ml_enqueue(&subframes, m);
1302 
1303 		m = n;
1304 		/* remove padding */
1305 		pad = ((len + 3) & ~3) - len;
1306 		m_adj(m, pad);
1307 	}
1308 
1309 	while ((n = ml_dequeue(&subframes)) != NULL)
1310 		ieee80211_enqueue_data(ic, n, ni, mcast, ml);
1311 
1312 	m_freem(m);
1313 }
1314 
1315 /*
1316  * Parse an EDCA Parameter Set element (see 7.3.2.27).
1317  */
1318 int
1319 ieee80211_parse_edca_params_body(struct ieee80211com *ic, const u_int8_t *frm)
1320 {
1321 	u_int updtcount;
1322 	int aci;
1323 
1324 	/*
1325 	 * Check if EDCA parameters have changed XXX if we miss more than
1326 	 * 15 consecutive beacons, we might not detect changes to EDCA
1327 	 * parameters due to wraparound of the 4-bit Update Count field.
1328 	 */
1329 	updtcount = frm[0] & 0xf;
1330 	if (updtcount == ic->ic_edca_updtcount)
1331 		return 0;	/* no changes to EDCA parameters, ignore */
1332 	ic->ic_edca_updtcount = updtcount;
1333 
1334 	frm += 2;	/* skip QoS Info & Reserved fields */
1335 
1336 	/* parse AC Parameter Records */
1337 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
1338 		struct ieee80211_edca_ac_params *ac = &ic->ic_edca_ac[aci];
1339 
1340 		ac->ac_acm       = (frm[0] >> 4) & 0x1;
1341 		ac->ac_aifsn     = frm[0] & 0xf;
1342 		ac->ac_ecwmin    = frm[1] & 0xf;
1343 		ac->ac_ecwmax    = frm[1] >> 4;
1344 		ac->ac_txoplimit = LE_READ_2(frm + 2);
1345 		frm += 4;
1346 	}
1347 	/* give drivers a chance to update their settings */
1348 	if ((ic->ic_flags & IEEE80211_F_QOS) && ic->ic_updateedca != NULL)
1349 		(*ic->ic_updateedca)(ic);
1350 
1351 	return 0;
1352 }
1353 
1354 int
1355 ieee80211_parse_edca_params(struct ieee80211com *ic, const u_int8_t *frm)
1356 {
1357 	if (frm[1] < 18) {
1358 		ic->ic_stats.is_rx_elem_toosmall++;
1359 		return IEEE80211_REASON_IE_INVALID;
1360 	}
1361 	return ieee80211_parse_edca_params_body(ic, frm + 2);
1362 }
1363 
1364 int
1365 ieee80211_parse_wmm_params(struct ieee80211com *ic, const u_int8_t *frm)
1366 {
1367 	if (frm[1] < 24) {
1368 		ic->ic_stats.is_rx_elem_toosmall++;
1369 		return IEEE80211_REASON_IE_INVALID;
1370 	}
1371 	return ieee80211_parse_edca_params_body(ic, frm + 8);
1372 }
1373 
1374 enum ieee80211_cipher
1375 ieee80211_parse_rsn_cipher(const u_int8_t selector[4])
1376 {
1377 	if (memcmp(selector, MICROSOFT_OUI, 3) == 0) {	/* WPA */
1378 		switch (selector[3]) {
1379 		case 0:	/* use group data cipher suite */
1380 			return IEEE80211_CIPHER_USEGROUP;
1381 		case 1:	/* WEP-40 */
1382 			return IEEE80211_CIPHER_WEP40;
1383 		case 2:	/* TKIP */
1384 			return IEEE80211_CIPHER_TKIP;
1385 		case 4:	/* CCMP (RSNA default) */
1386 			return IEEE80211_CIPHER_CCMP;
1387 		case 5:	/* WEP-104 */
1388 			return IEEE80211_CIPHER_WEP104;
1389 		}
1390 	} else if (memcmp(selector, IEEE80211_OUI, 3) == 0) {	/* RSN */
1391 		/* see 802.11-2012 Table 8-99 */
1392 		switch (selector[3]) {
1393 		case 0:	/* use group data cipher suite */
1394 			return IEEE80211_CIPHER_USEGROUP;
1395 		case 1:	/* WEP-40 */
1396 			return IEEE80211_CIPHER_WEP40;
1397 		case 2:	/* TKIP */
1398 			return IEEE80211_CIPHER_TKIP;
1399 		case 4:	/* CCMP (RSNA default) */
1400 			return IEEE80211_CIPHER_CCMP;
1401 		case 5:	/* WEP-104 */
1402 			return IEEE80211_CIPHER_WEP104;
1403 		case 6:	/* BIP */
1404 			return IEEE80211_CIPHER_BIP;
1405 		}
1406 	}
1407 	return IEEE80211_CIPHER_NONE;	/* ignore unknown ciphers */
1408 }
1409 
1410 enum ieee80211_akm
1411 ieee80211_parse_rsn_akm(const u_int8_t selector[4])
1412 {
1413 	if (memcmp(selector, MICROSOFT_OUI, 3) == 0) {	/* WPA */
1414 		switch (selector[3]) {
1415 		case 1:	/* IEEE 802.1X (RSNA default) */
1416 			return IEEE80211_AKM_8021X;
1417 		case 2:	/* PSK */
1418 			return IEEE80211_AKM_PSK;
1419 		}
1420 	} else if (memcmp(selector, IEEE80211_OUI, 3) == 0) {	/* RSN */
1421 		/* from IEEE Std 802.11i-2004 - Table 20dc */
1422 		switch (selector[3]) {
1423 		case 1:	/* IEEE 802.1X (RSNA default) */
1424 			return IEEE80211_AKM_8021X;
1425 		case 2:	/* PSK */
1426 			return IEEE80211_AKM_PSK;
1427 		case 5:	/* IEEE 802.1X with SHA256 KDF */
1428 			return IEEE80211_AKM_SHA256_8021X;
1429 		case 6:	/* PSK with SHA256 KDF */
1430 			return IEEE80211_AKM_SHA256_PSK;
1431 		}
1432 	}
1433 	return IEEE80211_AKM_NONE;	/* ignore unknown AKMs */
1434 }
1435 
1436 /*
1437  * Parse an RSN element (see 802.11-2012 8.4.2.27)
1438  */
1439 int
1440 ieee80211_parse_rsn_body(struct ieee80211com *ic, const u_int8_t *frm,
1441     u_int len, struct ieee80211_rsnparams *rsn)
1442 {
1443 	const u_int8_t *efrm;
1444 	u_int16_t m, n, s;
1445 
1446 	efrm = frm + len;
1447 
1448 	/* check Version field */
1449 	if (LE_READ_2(frm) != 1)
1450 		return IEEE80211_STATUS_RSN_IE_VER_UNSUP;
1451 	frm += 2;
1452 
1453 	/* all fields after the Version field are optional */
1454 
1455 	/* if Cipher Suite missing, default to CCMP */
1456 	rsn->rsn_groupcipher = IEEE80211_CIPHER_CCMP;
1457 	rsn->rsn_nciphers = 1;
1458 	rsn->rsn_ciphers = IEEE80211_CIPHER_CCMP;
1459 	/* if Group Management Cipher Suite missing, default to BIP */
1460 	rsn->rsn_groupmgmtcipher = IEEE80211_CIPHER_BIP;
1461 	/* if AKM Suite missing, default to 802.1X */
1462 	rsn->rsn_nakms = 1;
1463 	rsn->rsn_akms = IEEE80211_AKM_8021X;
1464 	/* if RSN capabilities missing, default to 0 */
1465 	rsn->rsn_caps = 0;
1466 	rsn->rsn_npmkids = 0;
1467 
1468 	/* read Group Data Cipher Suite field */
1469 	if (frm + 4 > efrm)
1470 		return 0;
1471 	rsn->rsn_groupcipher = ieee80211_parse_rsn_cipher(frm);
1472 	if (rsn->rsn_groupcipher == IEEE80211_CIPHER_NONE ||
1473 	    rsn->rsn_groupcipher == IEEE80211_CIPHER_USEGROUP ||
1474 	    rsn->rsn_groupcipher == IEEE80211_CIPHER_BIP)
1475 		return IEEE80211_STATUS_BAD_GROUP_CIPHER;
1476 	frm += 4;
1477 
1478 	/* read Pairwise Cipher Suite Count field */
1479 	if (frm + 2 > efrm)
1480 		return 0;
1481 	m = rsn->rsn_nciphers = LE_READ_2(frm);
1482 	frm += 2;
1483 
1484 	/* read Pairwise Cipher Suite List */
1485 	if (frm + m * 4 > efrm)
1486 		return IEEE80211_STATUS_IE_INVALID;
1487 	rsn->rsn_ciphers = IEEE80211_CIPHER_NONE;
1488 	while (m-- > 0) {
1489 		rsn->rsn_ciphers |= ieee80211_parse_rsn_cipher(frm);
1490 		frm += 4;
1491 	}
1492 	if (rsn->rsn_ciphers & IEEE80211_CIPHER_USEGROUP) {
1493 		if (rsn->rsn_ciphers != IEEE80211_CIPHER_USEGROUP)
1494 			return IEEE80211_STATUS_BAD_PAIRWISE_CIPHER;
1495 		if (rsn->rsn_groupcipher == IEEE80211_CIPHER_CCMP)
1496 			return IEEE80211_STATUS_BAD_PAIRWISE_CIPHER;
1497 	}
1498 
1499 	/* read AKM Suite List Count field */
1500 	if (frm + 2 > efrm)
1501 		return 0;
1502 	n = rsn->rsn_nakms = LE_READ_2(frm);
1503 	frm += 2;
1504 
1505 	/* read AKM Suite List */
1506 	if (frm + n * 4 > efrm)
1507 		return IEEE80211_STATUS_IE_INVALID;
1508 	rsn->rsn_akms = IEEE80211_AKM_NONE;
1509 	while (n-- > 0) {
1510 		rsn->rsn_akms |= ieee80211_parse_rsn_akm(frm);
1511 		frm += 4;
1512 	}
1513 
1514 	/* read RSN Capabilities field */
1515 	if (frm + 2 > efrm)
1516 		return 0;
1517 	rsn->rsn_caps = LE_READ_2(frm);
1518 	frm += 2;
1519 
1520 	/* read PMKID Count field */
1521 	if (frm + 2 > efrm)
1522 		return 0;
1523 	s = rsn->rsn_npmkids = LE_READ_2(frm);
1524 	frm += 2;
1525 
1526 	/* read PMKID List */
1527 	if (frm + s * IEEE80211_PMKID_LEN > efrm)
1528 		return IEEE80211_STATUS_IE_INVALID;
1529 	if (s != 0) {
1530 		rsn->rsn_pmkids = frm;
1531 		frm += s * IEEE80211_PMKID_LEN;
1532 	}
1533 
1534 	/* read Group Management Cipher Suite field */
1535 	if (frm + 4 > efrm)
1536 		return 0;
1537 	rsn->rsn_groupmgmtcipher = ieee80211_parse_rsn_cipher(frm);
1538 	if (rsn->rsn_groupmgmtcipher != IEEE80211_CIPHER_BIP)
1539 		return IEEE80211_STATUS_BAD_GROUP_CIPHER;
1540 
1541 	return IEEE80211_STATUS_SUCCESS;
1542 }
1543 
1544 int
1545 ieee80211_parse_rsn(struct ieee80211com *ic, const u_int8_t *frm,
1546     struct ieee80211_rsnparams *rsn)
1547 {
1548 	if (frm[1] < 2) {
1549 		ic->ic_stats.is_rx_elem_toosmall++;
1550 		return IEEE80211_STATUS_IE_INVALID;
1551 	}
1552 	return ieee80211_parse_rsn_body(ic, frm + 2, frm[1], rsn);
1553 }
1554 
1555 int
1556 ieee80211_parse_wpa(struct ieee80211com *ic, const u_int8_t *frm,
1557     struct ieee80211_rsnparams *rsn)
1558 {
1559 	if (frm[1] < 6) {
1560 		ic->ic_stats.is_rx_elem_toosmall++;
1561 		return IEEE80211_STATUS_IE_INVALID;
1562 	}
1563 	return ieee80211_parse_rsn_body(ic, frm + 6, frm[1] - 4, rsn);
1564 }
1565 
1566 /*
1567  * Create (or update) a copy of an information element.
1568  */
1569 int
1570 ieee80211_save_ie(const u_int8_t *frm, u_int8_t **ie)
1571 {
1572 	int olen = *ie ? 2 + (*ie)[1] : 0;
1573 	int len = 2 + frm[1];
1574 
1575 	if (*ie == NULL || olen != len) {
1576 		if (*ie != NULL)
1577 			free(*ie, M_DEVBUF, olen);
1578 		*ie = malloc(len, M_DEVBUF, M_NOWAIT);
1579 		if (*ie == NULL)
1580 			return ENOMEM;
1581 	}
1582 	memcpy(*ie, frm, len);
1583 	return 0;
1584 }
1585 
1586 /*-
1587  * Beacon/Probe response frame format:
1588  * [8]   Timestamp
1589  * [2]   Beacon interval
1590  * [2]   Capability
1591  * [tlv] Service Set Identifier (SSID)
1592  * [tlv] Supported rates
1593  * [tlv] DS Parameter Set (802.11g)
1594  * [tlv] ERP Information (802.11g)
1595  * [tlv] Extended Supported Rates (802.11g)
1596  * [tlv] RSN (802.11i)
1597  * [tlv] EDCA Parameter Set (802.11e)
1598  * [tlv] QoS Capability (Beacon only, 802.11e)
1599  * [tlv] HT Capabilities (802.11n)
1600  * [tlv] HT Operation (802.11n)
1601  */
1602 void
1603 ieee80211_recv_probe_resp(struct ieee80211com *ic, struct mbuf *m,
1604     struct ieee80211_node *rni, struct ieee80211_rxinfo *rxi, int isprobe)
1605 {
1606 	struct ieee80211_node *ni;
1607 	const struct ieee80211_frame *wh;
1608 	const u_int8_t *frm, *efrm;
1609 	const u_int8_t *tstamp, *ssid, *rates, *xrates, *edcaie, *wmmie, *tim;
1610 	const u_int8_t *rsnie, *wpaie, *htcaps, *htop, *vhtcaps, *vhtop;
1611 	u_int16_t capinfo, bintval;
1612 	u_int8_t chan, bchan, erp;
1613 	int is_new;
1614 
1615 	/*
1616 	 * We process beacon/probe response frames for:
1617 	 *    o station mode: to collect state
1618 	 *      updates such as 802.11g slot time and for passive
1619 	 *      scanning of APs
1620 	 *    o adhoc mode: to discover neighbors
1621 	 *    o hostap mode: for passive scanning of neighbor APs
1622 	 *    o when scanning
1623 	 * In other words, in all modes other than monitor (which
1624 	 * does not process incoming frames) and adhoc-demo (which
1625 	 * does not use management frames at all).
1626 	 */
1627 #ifdef DIAGNOSTIC
1628 	if (ic->ic_opmode != IEEE80211_M_STA &&
1629 #ifndef IEEE80211_STA_ONLY
1630 	    ic->ic_opmode != IEEE80211_M_IBSS &&
1631 	    ic->ic_opmode != IEEE80211_M_HOSTAP &&
1632 #endif
1633 	    ic->ic_state != IEEE80211_S_SCAN) {
1634 		panic("%s: impossible operating mode", __func__);
1635 	}
1636 #endif
1637 	/* make sure all mandatory fixed fields are present */
1638 	if (m->m_len < sizeof(*wh) + 12) {
1639 		DPRINTF(("frame too short\n"));
1640 		return;
1641 	}
1642 	wh = mtod(m, struct ieee80211_frame *);
1643 	frm = (const u_int8_t *)&wh[1];
1644 	efrm = mtod(m, u_int8_t *) + m->m_len;
1645 
1646 	tstamp  = frm; frm += 8;
1647 	bintval = LE_READ_2(frm); frm += 2;
1648 	capinfo = LE_READ_2(frm); frm += 2;
1649 
1650 	ssid = rates = xrates = edcaie = wmmie = rsnie = wpaie = tim = NULL;
1651 	htcaps = htop = vhtcaps = vhtop = NULL;
1652 	if (rxi->rxi_chan)
1653 		bchan = rxi->rxi_chan;
1654 	else
1655 		bchan = ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan);
1656 	chan = bchan;
1657 	erp = 0;
1658 	while (frm + 2 <= efrm) {
1659 		if (frm + 2 + frm[1] > efrm) {
1660 			ic->ic_stats.is_rx_elem_toosmall++;
1661 			break;
1662 		}
1663 		switch (frm[0]) {
1664 		case IEEE80211_ELEMID_SSID:
1665 			ssid = frm;
1666 			break;
1667 		case IEEE80211_ELEMID_RATES:
1668 			rates = frm;
1669 			break;
1670 		case IEEE80211_ELEMID_DSPARMS:
1671 			if (frm[1] < 1) {
1672 				ic->ic_stats.is_rx_elem_toosmall++;
1673 				break;
1674 			}
1675 			chan = frm[2];
1676 			break;
1677 		case IEEE80211_ELEMID_XRATES:
1678 			xrates = frm;
1679 			break;
1680 		case IEEE80211_ELEMID_ERP:
1681 			if (frm[1] < 1) {
1682 				ic->ic_stats.is_rx_elem_toosmall++;
1683 				break;
1684 			}
1685 			erp = frm[2];
1686 			break;
1687 		case IEEE80211_ELEMID_RSN:
1688 			rsnie = frm;
1689 			break;
1690 		case IEEE80211_ELEMID_EDCAPARMS:
1691 			edcaie = frm;
1692 			break;
1693 		case IEEE80211_ELEMID_HTCAPS:
1694 			htcaps = frm;
1695 			break;
1696 		case IEEE80211_ELEMID_HTOP:
1697 			if (frm[1] < 22) {
1698 				ic->ic_stats.is_rx_elem_toosmall++;
1699 				break;
1700 			}
1701 			htop = frm;
1702 			chan = frm[2];
1703 			break;
1704 		case IEEE80211_ELEMID_VHTCAPS:
1705 			vhtcaps = frm;
1706 			break;
1707 		case IEEE80211_ELEMID_VHTOP:
1708 			vhtop = frm;
1709 			break;
1710 		case IEEE80211_ELEMID_TIM:
1711 			if (frm[1] < 4) {
1712 				ic->ic_stats.is_rx_elem_toosmall++;
1713 				break;
1714 			}
1715 			tim = frm;
1716 			break;
1717 		case IEEE80211_ELEMID_VENDOR:
1718 			if (frm[1] < 4) {
1719 				ic->ic_stats.is_rx_elem_toosmall++;
1720 				break;
1721 			}
1722 			if (memcmp(frm + 2, MICROSOFT_OUI, 3) == 0) {
1723 				if (frm[5] == 1)
1724 					wpaie = frm;
1725 				else if (frm[1] >= 5 &&
1726 				    frm[5] == 2 && frm[6] == 1)
1727 					wmmie = frm;
1728 			}
1729 			break;
1730 		}
1731 		frm += 2 + frm[1];
1732 	}
1733 	/* supported rates element is mandatory */
1734 	if (rates == NULL || rates[1] > IEEE80211_RATE_MAXSIZE) {
1735 		DPRINTF(("invalid supported rates element\n"));
1736 		return;
1737 	}
1738 	/* SSID element is mandatory */
1739 	if (ssid == NULL || ssid[1] > IEEE80211_NWID_LEN) {
1740 		DPRINTF(("invalid SSID element\n"));
1741 		return;
1742 	}
1743 
1744 	if (
1745 #if IEEE80211_CHAN_MAX < 255
1746 	    chan > IEEE80211_CHAN_MAX ||
1747 #endif
1748 	    (isclr(ic->ic_chan_active, chan) &&
1749 	     ((ic->ic_caps & IEEE80211_C_SCANALL) == 0 ||
1750 	     (ic->ic_flags & IEEE80211_F_BGSCAN) == 0))) {
1751 		DPRINTF(("ignore %s with invalid channel %u\n",
1752 		    isprobe ? "probe response" : "beacon", chan));
1753 		ic->ic_stats.is_rx_badchan++;
1754 		return;
1755 	}
1756 	if ((rxi->rxi_chan != 0 && chan != rxi->rxi_chan) ||
1757 	    ((ic->ic_state != IEEE80211_S_SCAN ||
1758 	     !(ic->ic_caps & IEEE80211_C_SCANALL)) &&
1759 	    chan != bchan)) {
1760 		/*
1761 		 * Frame was received on a channel different from the
1762 		 * one indicated in the DS params element id;
1763 		 * silently discard it.
1764 		 *
1765 		 * NB: this can happen due to signal leakage.
1766 		 */
1767 		DPRINTF(("ignore %s on channel %u marked for channel %u\n",
1768 		    isprobe ? "probe response" : "beacon", bchan, chan));
1769 		ic->ic_stats.is_rx_chanmismatch++;
1770 		return;
1771 	}
1772 
1773 #ifdef IEEE80211_DEBUG
1774 	if (ieee80211_debug > 1 &&
1775 	    (ni == NULL || ic->ic_state == IEEE80211_S_SCAN ||
1776 	    (ic->ic_flags & IEEE80211_F_BGSCAN))) {
1777 		printf("%s: %s%s on chan %u (bss chan %u) ",
1778 		    __func__, (ni == NULL ? "new " : ""),
1779 		    isprobe ? "probe response" : "beacon",
1780 		    chan, bchan);
1781 		ieee80211_print_essid(ssid + 2, ssid[1]);
1782 		printf(" from %s\n", ether_sprintf((u_int8_t *)wh->i_addr2));
1783 		printf("%s: caps 0x%x bintval %u erp 0x%x\n",
1784 			__func__, capinfo, bintval, erp);
1785 	}
1786 #endif
1787 
1788 	if ((ni = ieee80211_find_node(ic, wh->i_addr2)) == NULL) {
1789 		ni = ieee80211_alloc_node(ic, wh->i_addr2);
1790 		if (ni == NULL)
1791 			return;
1792 		is_new = 1;
1793 	} else
1794 		is_new = 0;
1795 
1796 	ni->ni_chan = &ic->ic_channels[chan];
1797 
1798 	if (htcaps)
1799 		ieee80211_setup_htcaps(ni, htcaps + 2, htcaps[1]);
1800 	if (htop && !ieee80211_setup_htop(ni, htop + 2, htop[1], 1))
1801 		htop = NULL; /* invalid HTOP */
1802 	if (htcaps && vhtcaps && IEEE80211_IS_CHAN_5GHZ(ni->ni_chan)) {
1803 		ieee80211_setup_vhtcaps(ni, vhtcaps + 2, vhtcaps[1]);
1804 		if (vhtop && !ieee80211_setup_vhtop(ni, vhtop + 2, vhtop[1], 1))
1805 			vhtop = NULL; /* invalid VHTOP */
1806 	}
1807 
1808 	if (tim) {
1809 		ni->ni_dtimcount = tim[2];
1810 		ni->ni_dtimperiod = tim[3];
1811 	}
1812 
1813 	/*
1814 	 * When operating in station mode, check for state updates
1815 	 * while we're associated.
1816 	 */
1817 	if (ic->ic_opmode == IEEE80211_M_STA &&
1818 	    ic->ic_state == IEEE80211_S_RUN &&
1819 	    ni->ni_state == IEEE80211_STA_BSS) {
1820 		int updateprot = 0;
1821 		/*
1822 		 * Check if protection mode has changed since last beacon.
1823 		 */
1824 		if (ni->ni_erp != erp) {
1825 			DPRINTF(("[%s] erp change: was 0x%x, now 0x%x\n",
1826 			    ether_sprintf((u_int8_t *)wh->i_addr2),
1827 			    ni->ni_erp, erp));
1828 			if ((ic->ic_curmode == IEEE80211_MODE_11G ||
1829 			    (ic->ic_curmode == IEEE80211_MODE_11N &&
1830 			    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))) &&
1831 			    (erp & IEEE80211_ERP_USE_PROTECTION))
1832 				ic->ic_flags |= IEEE80211_F_USEPROT;
1833 			else
1834 				ic->ic_flags &= ~IEEE80211_F_USEPROT;
1835 			ic->ic_bss->ni_erp = erp;
1836 			updateprot = 1;
1837 		}
1838 		if (htop && (ic->ic_bss->ni_flags & IEEE80211_NODE_HT)) {
1839 			enum ieee80211_htprot htprot_last, htprot;
1840 			htprot_last =
1841 			    ((ic->ic_bss->ni_htop1 & IEEE80211_HTOP1_PROT_MASK)
1842 			    >> IEEE80211_HTOP1_PROT_SHIFT);
1843 			htprot = ((ni->ni_htop1 & IEEE80211_HTOP1_PROT_MASK) >>
1844 			    IEEE80211_HTOP1_PROT_SHIFT);
1845 			if (htprot_last != htprot) {
1846 				DPRINTF(("[%s] htprot change: was %d, now %d\n",
1847 				    ether_sprintf((u_int8_t *)wh->i_addr2),
1848 				    htprot_last, htprot));
1849 				ic->ic_stats.is_ht_prot_change++;
1850 				ic->ic_bss->ni_htop1 = ni->ni_htop1;
1851 				updateprot = 1;
1852 			}
1853 		}
1854 		if (updateprot && ic->ic_updateprot != NULL)
1855 			ic->ic_updateprot(ic);
1856 
1857 		/*
1858 		 * Check if 40MHz channel mode has changed since last beacon.
1859 		 */
1860 		if (htop && (ic->ic_bss->ni_flags & IEEE80211_NODE_HT) &&
1861 		    (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40)) {
1862 			uint8_t chw_last, chw, sco_last, sco;
1863 			chw_last = (ic->ic_bss->ni_htop0 & IEEE80211_HTOP0_CHW);
1864 			chw = (ni->ni_htop0 & IEEE80211_HTOP0_CHW);
1865 			sco_last =
1866 			    ((ic->ic_bss->ni_htop0 & IEEE80211_HTOP0_SCO_MASK)
1867 			    >> IEEE80211_HTOP0_SCO_SHIFT);
1868 			sco = ((ni->ni_htop0 & IEEE80211_HTOP0_SCO_MASK) >>
1869 			    IEEE80211_HTOP0_SCO_SHIFT);
1870 			ic->ic_bss->ni_htop0 = ni->ni_htop0;
1871 			if (chw_last != chw || sco_last != sco) {
1872 				if (ic->ic_updatechan != NULL)
1873 					ic->ic_updatechan(ic);
1874 			}
1875 		} else if (htop)
1876 			ic->ic_bss->ni_htop0 = ni->ni_htop0;
1877 
1878 		/*
1879 		 * Check if AP short slot time setting has changed
1880 		 * since last beacon and give the driver a chance to
1881 		 * update the hardware.
1882 		 */
1883 		if ((ni->ni_capinfo ^ capinfo) &
1884 		    IEEE80211_CAPINFO_SHORT_SLOTTIME) {
1885 			ieee80211_set_shortslottime(ic,
1886 			    ic->ic_curmode == IEEE80211_MODE_11A ||
1887 			    (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME));
1888 		}
1889 
1890 		if (tim && ic->ic_bss->ni_dtimperiod != ni->ni_dtimperiod) {
1891 			ic->ic_bss->ni_dtimperiod = ni->ni_dtimperiod;
1892 			ic->ic_bss->ni_dtimcount = ni->ni_dtimcount;
1893 
1894 			if (ic->ic_updatedtim != NULL)
1895 				ic->ic_updatedtim(ic);
1896 		}
1897 
1898 		/*
1899 		 * Reset management timer. If it is non-zero in RUN state, the
1900 		 * driver sent a probe request after a missed beacon event.
1901 		 * This probe response indicates the AP is still serving us
1902 		 * so don't allow ieee80211_watchdog() to move us into SCAN.
1903 		 */
1904 		 if ((ic->ic_flags & IEEE80211_F_BGSCAN) == 0)
1905 		 	ic->ic_mgt_timer = 0;
1906 	}
1907 	/*
1908 	 * We do not try to update EDCA parameters if QoS was not negotiated
1909 	 * with the AP at association time.
1910 	 */
1911 	if (ni->ni_flags & IEEE80211_NODE_QOS) {
1912 		/* always prefer EDCA IE over Wi-Fi Alliance WMM IE */
1913 		if ((edcaie != NULL &&
1914 		     ieee80211_parse_edca_params(ic, edcaie) == 0) ||
1915 		    (wmmie != NULL &&
1916 		     ieee80211_parse_wmm_params(ic, wmmie) == 0))
1917 			ni->ni_flags |= IEEE80211_NODE_QOS;
1918 		else
1919 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
1920 	}
1921 
1922 	if (ic->ic_state == IEEE80211_S_SCAN ||
1923 	    (ic->ic_flags & IEEE80211_F_BGSCAN)) {
1924 		struct ieee80211_rsnparams rsn, wpa;
1925 
1926 		ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
1927 		ni->ni_supported_rsnprotos = IEEE80211_PROTO_NONE;
1928 		ni->ni_rsnakms = 0;
1929 		ni->ni_supported_rsnakms = 0;
1930 		ni->ni_rsnciphers = 0;
1931 		ni->ni_rsngroupcipher = 0;
1932 		ni->ni_rsngroupmgmtcipher = 0;
1933 		ni->ni_rsncaps = 0;
1934 
1935 		if (rsnie != NULL &&
1936 		    ieee80211_parse_rsn(ic, rsnie, &rsn) == 0) {
1937 			ni->ni_supported_rsnprotos |= IEEE80211_PROTO_RSN;
1938 			ni->ni_supported_rsnakms |= rsn.rsn_akms;
1939 		}
1940 		if (wpaie != NULL &&
1941 		    ieee80211_parse_wpa(ic, wpaie, &wpa) == 0) {
1942 			ni->ni_supported_rsnprotos |= IEEE80211_PROTO_WPA;
1943 			ni->ni_supported_rsnakms |= wpa.rsn_akms;
1944 		}
1945 
1946 		/*
1947 		 * If the AP advertises both WPA and RSN IEs (WPA1+WPA2),
1948 		 * we only use the highest protocol version we support.
1949 		 */
1950 		if (rsnie != NULL &&
1951 		    (ni->ni_supported_rsnprotos & IEEE80211_PROTO_RSN) &&
1952 		    (ic->ic_caps & IEEE80211_C_RSN)) {
1953 			if (ieee80211_save_ie(rsnie, &ni->ni_rsnie) == 0
1954 #ifndef IEEE80211_STA_ONLY
1955 	    		&& ic->ic_opmode != IEEE80211_M_HOSTAP
1956 #endif
1957 			) {
1958 				ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
1959 				ni->ni_rsnakms = rsn.rsn_akms;
1960 				ni->ni_rsnciphers = rsn.rsn_ciphers;
1961 				ni->ni_rsngroupcipher = rsn.rsn_groupcipher;
1962 				ni->ni_rsngroupmgmtcipher =
1963 				    rsn.rsn_groupmgmtcipher;
1964 				ni->ni_rsncaps = rsn.rsn_caps;
1965 			}
1966 		} else if (wpaie != NULL &&
1967 		    (ni->ni_supported_rsnprotos & IEEE80211_PROTO_WPA) &&
1968 		    (ic->ic_caps & IEEE80211_C_RSN)) {
1969 			if (ieee80211_save_ie(wpaie, &ni->ni_rsnie) == 0
1970 #ifndef IEEE80211_STA_ONLY
1971 	    		&& ic->ic_opmode != IEEE80211_M_HOSTAP
1972 #endif
1973 			) {
1974 				ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
1975 				ni->ni_rsnakms = wpa.rsn_akms;
1976 				ni->ni_rsnciphers = wpa.rsn_ciphers;
1977 				ni->ni_rsngroupcipher = wpa.rsn_groupcipher;
1978 				ni->ni_rsngroupmgmtcipher =
1979 				    wpa.rsn_groupmgmtcipher;
1980 				ni->ni_rsncaps = wpa.rsn_caps;
1981 			}
1982 		}
1983 	}
1984 
1985 	/*
1986 	 * Set our SSID if we do not know it yet.
1987 	 * If we are doing a directed scan for an AP with a hidden SSID
1988 	 * we must collect the SSID from a probe response to override
1989 	 * a non-zero-length SSID filled with zeroes that we may have
1990 	 * received earlier in a beacon.
1991 	 */
1992 	if (ssid[1] != 0 && ni->ni_essid[0] == '\0') {
1993 		ni->ni_esslen = ssid[1];
1994 		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
1995 		/* we know that ssid[1] <= IEEE80211_NWID_LEN */
1996 		memcpy(ni->ni_essid, &ssid[2], ssid[1]);
1997 	}
1998 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1999 	if (ic->ic_state == IEEE80211_S_SCAN &&
2000 	    IEEE80211_IS_CHAN_5GHZ(ni->ni_chan)) {
2001 		/*
2002 		 * During a scan on 5Ghz, prefer RSSI measured for probe
2003 		 * response frames. i.e. don't allow beacons to lower the
2004 		 * measured RSSI. Some 5GHz APs send beacons with much
2005 		 * less Tx power than they use for probe responses.
2006 		 */
2007 		if (isprobe || ni->ni_rssi == 0)
2008 			ni->ni_rssi = rxi->rxi_rssi;
2009 		else if (ni->ni_rssi < rxi->rxi_rssi)
2010 			ni->ni_rssi = rxi->rxi_rssi;
2011 	} else
2012 		ni->ni_rssi = rxi->rxi_rssi;
2013 	ni->ni_rstamp = rxi->rxi_tstamp;
2014 	memcpy(ni->ni_tstamp, tstamp, sizeof(ni->ni_tstamp));
2015 	ni->ni_intval = bintval;
2016 	ni->ni_capinfo = capinfo;
2017 	ni->ni_erp = erp;
2018 	/* NB: must be after ni_chan is setup */
2019 	ieee80211_setup_rates(ic, ni, rates, xrates, IEEE80211_F_DOSORT);
2020 #ifndef IEEE80211_STA_ONLY
2021 	if (ic->ic_opmode == IEEE80211_M_IBSS && is_new && isprobe) {
2022 		/*
2023 		 * Fake an association so the driver can setup its
2024 		 * private state.  The rate set has been setup above;
2025 		 * there is no handshake as in ap/station operation.
2026 		 */
2027 		if (ic->ic_newassoc)
2028 			(*ic->ic_newassoc)(ic, ni, 1);
2029 	}
2030 #endif
2031 }
2032 
2033 #ifndef IEEE80211_STA_ONLY
2034 /*-
2035  * Probe request frame format:
2036  * [tlv] SSID
2037  * [tlv] Supported rates
2038  * [tlv] Extended Supported Rates (802.11g)
2039  * [tlv] HT Capabilities (802.11n)
2040  */
2041 void
2042 ieee80211_recv_probe_req(struct ieee80211com *ic, struct mbuf *m,
2043     struct ieee80211_node *ni, struct ieee80211_rxinfo *rxi)
2044 {
2045 	const struct ieee80211_frame *wh;
2046 	const u_int8_t *frm, *efrm;
2047 	const u_int8_t *ssid, *rates, *xrates, *htcaps, *vhtcaps;
2048 	u_int8_t rate;
2049 
2050 	if (ic->ic_opmode == IEEE80211_M_STA ||
2051 	    ic->ic_state != IEEE80211_S_RUN)
2052 		return;
2053 
2054 	wh = mtod(m, struct ieee80211_frame *);
2055 	frm = (const u_int8_t *)&wh[1];
2056 	efrm = mtod(m, u_int8_t *) + m->m_len;
2057 
2058 	ssid = rates = xrates = htcaps = vhtcaps = NULL;
2059 	while (frm + 2 <= efrm) {
2060 		if (frm + 2 + frm[1] > efrm) {
2061 			ic->ic_stats.is_rx_elem_toosmall++;
2062 			break;
2063 		}
2064 		switch (frm[0]) {
2065 		case IEEE80211_ELEMID_SSID:
2066 			ssid = frm;
2067 			break;
2068 		case IEEE80211_ELEMID_RATES:
2069 			rates = frm;
2070 			break;
2071 		case IEEE80211_ELEMID_XRATES:
2072 			xrates = frm;
2073 			break;
2074 		case IEEE80211_ELEMID_HTCAPS:
2075 			htcaps = frm;
2076 			break;
2077 		case IEEE80211_ELEMID_VHTCAPS:
2078 			vhtcaps = frm;
2079 			break;
2080 		}
2081 		frm += 2 + frm[1];
2082 	}
2083 	/* supported rates element is mandatory */
2084 	if (rates == NULL || rates[1] > IEEE80211_RATE_MAXSIZE) {
2085 		DPRINTF(("invalid supported rates element\n"));
2086 		return;
2087 	}
2088 	/* SSID element is mandatory */
2089 	if (ssid == NULL || ssid[1] > IEEE80211_NWID_LEN) {
2090 		DPRINTF(("invalid SSID element\n"));
2091 		return;
2092 	}
2093 	/* check that the specified SSID (if not wildcard) matches ours */
2094 	if (ssid[1] != 0 && (ssid[1] != ic->ic_bss->ni_esslen ||
2095 	    memcmp(&ssid[2], ic->ic_bss->ni_essid, ic->ic_bss->ni_esslen))) {
2096 		DPRINTF(("SSID mismatch\n"));
2097 		ic->ic_stats.is_rx_ssidmismatch++;
2098 		return;
2099 	}
2100 	/* refuse wildcard SSID if we're hiding our SSID in beacons */
2101 	if (ssid[1] == 0 && (ic->ic_userflags & IEEE80211_F_HIDENWID)) {
2102 		DPRINTF(("wildcard SSID rejected"));
2103 		ic->ic_stats.is_rx_ssidmismatch++;
2104 		return;
2105 	}
2106 
2107 	if (ni == ic->ic_bss) {
2108 		ni = ieee80211_find_node(ic, wh->i_addr2);
2109 		if (ni == NULL)
2110 			ni = ieee80211_dup_bss(ic, wh->i_addr2);
2111 		if (ni == NULL)
2112 			return;
2113 		DPRINTF(("new probe req from %s\n",
2114 		    ether_sprintf((u_int8_t *)wh->i_addr2)));
2115 	}
2116 	ni->ni_rssi = rxi->rxi_rssi;
2117 	ni->ni_rstamp = rxi->rxi_tstamp;
2118 	rate = ieee80211_setup_rates(ic, ni, rates, xrates,
2119 	    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE | IEEE80211_F_DONEGO |
2120 	    IEEE80211_F_DODEL);
2121 	if (rate & IEEE80211_RATE_BASIC) {
2122 		DPRINTF(("rate mismatch for %s\n",
2123 		    ether_sprintf((u_int8_t *)wh->i_addr2)));
2124 		return;
2125 	}
2126 	if (htcaps)
2127 		ieee80211_setup_htcaps(ni, htcaps + 2, htcaps[1]);
2128 	else
2129 		ieee80211_clear_htcaps(ni);
2130 	if (htcaps && vhtcaps && IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2131 		ieee80211_setup_vhtcaps(ni, vhtcaps + 2, vhtcaps[1]);
2132 	else
2133 		ieee80211_clear_vhtcaps(ni);
2134 	IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_PROBE_RESP, 0);
2135 }
2136 #endif	/* IEEE80211_STA_ONLY */
2137 
2138 /*-
2139  * Authentication frame format:
2140  * [2] Authentication algorithm number
2141  * [2] Authentication transaction sequence number
2142  * [2] Status code
2143  */
2144 void
2145 ieee80211_recv_auth(struct ieee80211com *ic, struct mbuf *m,
2146     struct ieee80211_node *ni, struct ieee80211_rxinfo *rxi)
2147 {
2148 	const struct ieee80211_frame *wh;
2149 	const u_int8_t *frm;
2150 	u_int16_t algo, seq, status;
2151 
2152 	/* make sure all mandatory fixed fields are present */
2153 	if (m->m_len < sizeof(*wh) + 6) {
2154 		DPRINTF(("frame too short\n"));
2155 		return;
2156 	}
2157 	wh = mtod(m, struct ieee80211_frame *);
2158 	frm = (const u_int8_t *)&wh[1];
2159 
2160 	algo   = LE_READ_2(frm); frm += 2;
2161 	seq    = LE_READ_2(frm); frm += 2;
2162 	status = LE_READ_2(frm); frm += 2;
2163 	DPRINTF(("auth %d seq %d from %s\n", algo, seq,
2164 	    ether_sprintf((u_int8_t *)wh->i_addr2)));
2165 
2166 	/* only "open" auth mode is supported */
2167 	if (algo != IEEE80211_AUTH_ALG_OPEN) {
2168 		DPRINTF(("unsupported auth algorithm %d from %s\n",
2169 		    algo, ether_sprintf((u_int8_t *)wh->i_addr2)));
2170 		ic->ic_stats.is_rx_auth_unsupported++;
2171 #ifndef IEEE80211_STA_ONLY
2172 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2173 			/* XXX hack to workaround calling convention */
2174 			IEEE80211_SEND_MGMT(ic, ni,
2175 			    IEEE80211_FC0_SUBTYPE_AUTH,
2176 			    IEEE80211_STATUS_ALG << 16 | ((seq + 1) & 0xfff));
2177 		}
2178 #endif
2179 		return;
2180 	}
2181 	ieee80211_auth_open(ic, wh, ni, rxi, seq, status);
2182 }
2183 
2184 #ifndef IEEE80211_STA_ONLY
2185 /*-
2186  * (Re)Association request frame format:
2187  * [2]   Capability information
2188  * [2]   Listen interval
2189  * [6*]  Current AP address (Reassociation only)
2190  * [tlv] SSID
2191  * [tlv] Supported rates
2192  * [tlv] Extended Supported Rates (802.11g)
2193  * [tlv] RSN (802.11i)
2194  * [tlv] QoS Capability (802.11e)
2195  * [tlv] HT Capabilities (802.11n)
2196  */
2197 void
2198 ieee80211_recv_assoc_req(struct ieee80211com *ic, struct mbuf *m,
2199     struct ieee80211_node *ni, struct ieee80211_rxinfo *rxi, int reassoc)
2200 {
2201 	const struct ieee80211_frame *wh;
2202 	const u_int8_t *frm, *efrm;
2203 	const u_int8_t *ssid, *rates, *xrates, *rsnie, *wpaie, *wmeie;
2204 	const u_int8_t *htcaps, *vhtcaps;
2205 	u_int16_t capinfo, bintval;
2206 	int resp, status = 0;
2207 	struct ieee80211_rsnparams rsn;
2208 	u_int8_t rate;
2209 	const u_int8_t *saveie = NULL;
2210 
2211 	if (ic->ic_opmode != IEEE80211_M_HOSTAP ||
2212 	    ic->ic_state != IEEE80211_S_RUN)
2213 		return;
2214 
2215 	/* make sure all mandatory fixed fields are present */
2216 	if (m->m_len < sizeof(*wh) + (reassoc ? 10 : 4)) {
2217 		DPRINTF(("frame too short\n"));
2218 		return;
2219 	}
2220 	wh = mtod(m, struct ieee80211_frame *);
2221 	frm = (const u_int8_t *)&wh[1];
2222 	efrm = mtod(m, u_int8_t *) + m->m_len;
2223 
2224 	if (!IEEE80211_ADDR_EQ(wh->i_addr3, ic->ic_bss->ni_bssid)) {
2225 		DPRINTF(("ignore other bss from %s\n",
2226 		    ether_sprintf((u_int8_t *)wh->i_addr2)));
2227 		ic->ic_stats.is_rx_assoc_bss++;
2228 		return;
2229 	}
2230 	capinfo = LE_READ_2(frm); frm += 2;
2231 	bintval = LE_READ_2(frm); frm += 2;
2232 	if (reassoc) {
2233 		frm += IEEE80211_ADDR_LEN;	/* skip current AP address */
2234 		resp = IEEE80211_FC0_SUBTYPE_REASSOC_RESP;
2235 	} else
2236 		resp = IEEE80211_FC0_SUBTYPE_ASSOC_RESP;
2237 
2238 	ssid = rates = xrates = rsnie = wpaie = wmeie = htcaps = vhtcaps = NULL;
2239 	while (frm + 2 <= efrm) {
2240 		if (frm + 2 + frm[1] > efrm) {
2241 			ic->ic_stats.is_rx_elem_toosmall++;
2242 			break;
2243 		}
2244 		switch (frm[0]) {
2245 		case IEEE80211_ELEMID_SSID:
2246 			ssid = frm;
2247 			break;
2248 		case IEEE80211_ELEMID_RATES:
2249 			rates = frm;
2250 			break;
2251 		case IEEE80211_ELEMID_XRATES:
2252 			xrates = frm;
2253 			break;
2254 		case IEEE80211_ELEMID_RSN:
2255 			rsnie = frm;
2256 			break;
2257 		case IEEE80211_ELEMID_QOS_CAP:
2258 			break;
2259 		case IEEE80211_ELEMID_HTCAPS:
2260 			htcaps = frm;
2261 			break;
2262 		case IEEE80211_ELEMID_VHTCAPS:
2263 			vhtcaps = frm;
2264 			break;
2265 		case IEEE80211_ELEMID_VENDOR:
2266 			if (frm[1] < 4) {
2267 				ic->ic_stats.is_rx_elem_toosmall++;
2268 				break;
2269 			}
2270 			if (memcmp(frm + 2, MICROSOFT_OUI, 3) == 0) {
2271 				if (frm[5] == 1)
2272 					wpaie = frm;
2273 				/* WME info IE: len=7 type=2 subtype=0 */
2274 				if (frm[1] == 7 && frm[5] == 2 && frm[6] == 0)
2275 					wmeie = frm;
2276 			}
2277 			break;
2278 		}
2279 		frm += 2 + frm[1];
2280 	}
2281 	/* supported rates element is mandatory */
2282 	if (rates == NULL || rates[1] > IEEE80211_RATE_MAXSIZE) {
2283 		DPRINTF(("invalid supported rates element\n"));
2284 		return;
2285 	}
2286 	/* SSID element is mandatory */
2287 	if (ssid == NULL || ssid[1] > IEEE80211_NWID_LEN) {
2288 		DPRINTF(("invalid SSID element\n"));
2289 		return;
2290 	}
2291 	/* check that the specified SSID matches ours */
2292 	if (ssid[1] != ic->ic_bss->ni_esslen ||
2293 	    memcmp(&ssid[2], ic->ic_bss->ni_essid, ic->ic_bss->ni_esslen)) {
2294 		DPRINTF(("SSID mismatch\n"));
2295 		ic->ic_stats.is_rx_ssidmismatch++;
2296 		return;
2297 	}
2298 
2299 	if (ni->ni_state != IEEE80211_STA_AUTH &&
2300 	    ni->ni_state != IEEE80211_STA_ASSOC) {
2301 		DPRINTF(("deny %sassoc from %s, not authenticated\n",
2302 		    reassoc ? "re" : "",
2303 		    ether_sprintf((u_int8_t *)wh->i_addr2)));
2304 		ni = ieee80211_find_node(ic, wh->i_addr2);
2305 		if (ni == NULL)
2306 			ni = ieee80211_dup_bss(ic, wh->i_addr2);
2307 		if (ni != NULL) {
2308 			IEEE80211_SEND_MGMT(ic, ni,
2309 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2310 			    IEEE80211_REASON_ASSOC_NOT_AUTHED);
2311 		}
2312 		ic->ic_stats.is_rx_assoc_notauth++;
2313 		return;
2314 	}
2315 
2316 	if (ni->ni_state == IEEE80211_STA_ASSOC &&
2317 	    (ni->ni_flags & IEEE80211_NODE_MFP)) {
2318 		if (ni->ni_flags & IEEE80211_NODE_SA_QUERY_FAILED) {
2319 			/* send a protected Disassociate frame */
2320 			IEEE80211_SEND_MGMT(ic, ni,
2321 			    IEEE80211_FC0_SUBTYPE_DISASSOC,
2322 			    IEEE80211_REASON_AUTH_EXPIRE);
2323 			/* terminate the old SA */
2324 			ieee80211_node_leave(ic, ni);
2325 		} else {
2326 			/* reject the (Re)Association Request temporarily */
2327 			IEEE80211_SEND_MGMT(ic, ni, resp,
2328 			    IEEE80211_STATUS_TRY_AGAIN_LATER);
2329 			/* start SA Query procedure if not already engaged */
2330 			if (!(ni->ni_flags & IEEE80211_NODE_SA_QUERY))
2331 				ieee80211_sa_query_request(ic, ni);
2332 			/* do not modify association state */
2333 		}
2334 		return;
2335 	}
2336 
2337 	if (!(capinfo & IEEE80211_CAPINFO_ESS)) {
2338 		ic->ic_stats.is_rx_assoc_capmismatch++;
2339 		status = IEEE80211_STATUS_CAPINFO;
2340 		goto end;
2341 	}
2342 	rate = ieee80211_setup_rates(ic, ni, rates, xrates,
2343 	    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE | IEEE80211_F_DONEGO |
2344 	    IEEE80211_F_DODEL);
2345 	if (rate & IEEE80211_RATE_BASIC) {
2346 		ic->ic_stats.is_rx_assoc_norate++;
2347 		status = IEEE80211_STATUS_BASIC_RATE;
2348 		goto end;
2349 	}
2350 
2351 	ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2352 	ni->ni_supported_rsnprotos = IEEE80211_PROTO_NONE;
2353 	ni->ni_rsnakms = 0;
2354 	ni->ni_supported_rsnakms = 0;
2355 	ni->ni_rsnciphers = 0;
2356 	ni->ni_rsngroupcipher = 0;
2357 	ni->ni_rsngroupmgmtcipher = 0;
2358 	ni->ni_rsncaps = 0;
2359 
2360 	/*
2361 	 * A station should never include both a WPA and an RSN IE
2362 	 * in its (Re)Association Requests, but if it does, we only
2363 	 * consider the IE of the highest version of the protocol
2364 	 * that is allowed (ie RSN over WPA).
2365 	 */
2366 	if (rsnie != NULL) {
2367 		status = ieee80211_parse_rsn(ic, rsnie, &rsn);
2368 		if (status != 0)
2369 			goto end;
2370 		ni->ni_supported_rsnprotos = IEEE80211_PROTO_RSN;
2371 		ni->ni_supported_rsnakms = rsn.rsn_akms;
2372 		if ((ic->ic_flags & IEEE80211_F_RSNON) &&
2373 		    (ic->ic_rsnprotos & IEEE80211_PROTO_RSN)) {
2374 			ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
2375 			saveie = rsnie;
2376 		}
2377 	} else if (wpaie != NULL) {
2378 		status = ieee80211_parse_wpa(ic, wpaie, &rsn);
2379 		if (status != 0)
2380 			goto end;
2381 		ni->ni_supported_rsnprotos = IEEE80211_PROTO_WPA;
2382 		ni->ni_supported_rsnakms = rsn.rsn_akms;
2383 		if ((ic->ic_flags & IEEE80211_F_RSNON) &&
2384 		    (ic->ic_rsnprotos & IEEE80211_PROTO_WPA)) {
2385 			ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
2386 			saveie = wpaie;
2387 		}
2388 	}
2389 
2390 	if (ic->ic_flags & IEEE80211_F_QOS) {
2391 		if (wmeie != NULL)
2392 			ni->ni_flags |= IEEE80211_NODE_QOS;
2393 		else	/* for Reassociation */
2394 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
2395 	}
2396 
2397 	if (ic->ic_flags & IEEE80211_F_RSNON) {
2398 		if (ni->ni_rsnprotos == IEEE80211_PROTO_NONE) {
2399 			/*
2400 			 * In an RSN, an AP shall not associate with STAs
2401 			 * that fail to include the RSN IE in the
2402 			 * (Re)Association Request.
2403 			 */
2404 			status = IEEE80211_STATUS_IE_INVALID;
2405 			goto end;
2406 		}
2407 		/*
2408 		 * The initiating STA's RSN IE shall include one authentication
2409 		 * and pairwise cipher suite among those advertised by the
2410 		 * targeted AP.  It shall also specify the group cipher suite
2411 		 * specified by the targeted AP.
2412 		 */
2413 		if (rsn.rsn_nakms != 1 ||
2414 		    !(rsn.rsn_akms & ic->ic_bss->ni_rsnakms)) {
2415 			status = IEEE80211_STATUS_BAD_AKMP;
2416 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2417 			goto end;
2418 		}
2419 		if (rsn.rsn_nciphers != 1 ||
2420 		    !(rsn.rsn_ciphers & ic->ic_bss->ni_rsnciphers)) {
2421 			status = IEEE80211_STATUS_BAD_PAIRWISE_CIPHER;
2422 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2423 			goto end;
2424 		}
2425 		if (rsn.rsn_groupcipher != ic->ic_bss->ni_rsngroupcipher) {
2426 			status = IEEE80211_STATUS_BAD_GROUP_CIPHER;
2427 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2428 			goto end;
2429 		}
2430 
2431 		if ((ic->ic_bss->ni_rsncaps & IEEE80211_RSNCAP_MFPR) &&
2432 		    !(rsn.rsn_caps & IEEE80211_RSNCAP_MFPC)) {
2433 			status = IEEE80211_STATUS_MFP_POLICY;
2434 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2435 			goto end;
2436 		}
2437 		if ((ic->ic_bss->ni_rsncaps & IEEE80211_RSNCAP_MFPC) &&
2438 		    (rsn.rsn_caps & (IEEE80211_RSNCAP_MFPC |
2439 		     IEEE80211_RSNCAP_MFPR)) == IEEE80211_RSNCAP_MFPR) {
2440 			/* STA advertises an invalid setting */
2441 			status = IEEE80211_STATUS_MFP_POLICY;
2442 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2443 			goto end;
2444 		}
2445 		/*
2446 		 * A STA that has associated with Management Frame Protection
2447 		 * enabled shall not use cipher suite pairwise selector WEP40,
2448 		 * WEP104, TKIP, or "Use Group cipher suite".
2449 		 */
2450 		if ((rsn.rsn_caps & IEEE80211_RSNCAP_MFPC) &&
2451 		    (rsn.rsn_ciphers != IEEE80211_CIPHER_CCMP ||
2452 		     rsn.rsn_groupmgmtcipher !=
2453 		     ic->ic_bss->ni_rsngroupmgmtcipher)) {
2454 			status = IEEE80211_STATUS_MFP_POLICY;
2455 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2456 			goto end;
2457 		}
2458 
2459 		/*
2460 		 * Disallow new associations using TKIP if countermeasures
2461 		 * are active.
2462 		 */
2463 		if ((ic->ic_flags & IEEE80211_F_COUNTERM) &&
2464 		    (rsn.rsn_ciphers == IEEE80211_CIPHER_TKIP ||
2465 		     rsn.rsn_groupcipher == IEEE80211_CIPHER_TKIP)) {
2466 			status = IEEE80211_STATUS_CIPHER_REJ_POLICY;
2467 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2468 			goto end;
2469 		}
2470 
2471 		/* everything looks fine, save IE and parameters */
2472 		if (saveie == NULL ||
2473 		    ieee80211_save_ie(saveie, &ni->ni_rsnie) != 0) {
2474 			status = IEEE80211_STATUS_TOOMANY;
2475 			ni->ni_rsnprotos = IEEE80211_PROTO_NONE;
2476 			goto end;
2477 		}
2478 		ni->ni_rsnakms = rsn.rsn_akms;
2479 		ni->ni_rsnciphers = rsn.rsn_ciphers;
2480 		ni->ni_rsngroupcipher = ic->ic_bss->ni_rsngroupcipher;
2481 		ni->ni_rsngroupmgmtcipher = ic->ic_bss->ni_rsngroupmgmtcipher;
2482 		ni->ni_rsncaps = rsn.rsn_caps;
2483 
2484 		if (ieee80211_is_8021x_akm(ni->ni_rsnakms)) {
2485 			struct ieee80211_pmk *pmk = NULL;
2486 			const u_int8_t *pmkid = rsn.rsn_pmkids;
2487 			/*
2488 			 * Check if we have a cached PMK entry matching one
2489 			 * of the PMKIDs specified in the RSN IE.
2490 			 */
2491 			while (rsn.rsn_npmkids-- > 0) {
2492 				pmk = ieee80211_pmksa_find(ic, ni, pmkid);
2493 				if (pmk != NULL)
2494 					break;
2495 				pmkid += IEEE80211_PMKID_LEN;
2496 			}
2497 			if (pmk != NULL) {
2498 				memcpy(ni->ni_pmk, pmk->pmk_key,
2499 				    IEEE80211_PMK_LEN);
2500 				memcpy(ni->ni_pmkid, pmk->pmk_pmkid,
2501 				    IEEE80211_PMKID_LEN);
2502 				ni->ni_flags |= IEEE80211_NODE_PMK;
2503 			}
2504 		}
2505 	}
2506 
2507 	ni->ni_rssi = rxi->rxi_rssi;
2508 	ni->ni_rstamp = rxi->rxi_tstamp;
2509 	ni->ni_intval = bintval;
2510 	ni->ni_capinfo = capinfo;
2511 	ni->ni_chan = ic->ic_bss->ni_chan;
2512 	if (htcaps)
2513 		ieee80211_setup_htcaps(ni, htcaps + 2, htcaps[1]);
2514 	else
2515 		ieee80211_clear_htcaps(ni);
2516 	if (htcaps && vhtcaps && IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2517 		ieee80211_setup_vhtcaps(ni, vhtcaps + 2, vhtcaps[1]);
2518 	else
2519 		ieee80211_clear_vhtcaps(ni);
2520  end:
2521 	if (status != 0) {
2522 		IEEE80211_SEND_MGMT(ic, ni, resp, status);
2523 		ieee80211_node_leave(ic, ni);
2524 	} else
2525 		ieee80211_node_join(ic, ni, resp);
2526 }
2527 #endif	/* IEEE80211_STA_ONLY */
2528 
2529 /*-
2530  * (Re)Association response frame format:
2531  * [2]   Capability information
2532  * [2]   Status code
2533  * [2]   Association ID (AID)
2534  * [tlv] Supported rates
2535  * [tlv] Extended Supported Rates (802.11g)
2536  * [tlv] EDCA Parameter Set (802.11e)
2537  * [tlv] HT Capabilities (802.11n)
2538  * [tlv] HT Operation (802.11n)
2539  */
2540 void
2541 ieee80211_recv_assoc_resp(struct ieee80211com *ic, struct mbuf *m,
2542     struct ieee80211_node *ni, int reassoc)
2543 {
2544 	struct ifnet *ifp = &ic->ic_if;
2545 	const struct ieee80211_frame *wh;
2546 	const u_int8_t *frm, *efrm;
2547 	const u_int8_t *rates, *xrates, *edcaie, *wmmie, *htcaps, *htop;
2548 	const u_int8_t *vhtcaps, *vhtop;
2549 	u_int16_t capinfo, status, associd;
2550 	u_int8_t rate;
2551 
2552 	if (ic->ic_opmode != IEEE80211_M_STA ||
2553 	    ic->ic_state != IEEE80211_S_ASSOC) {
2554 		ic->ic_stats.is_rx_mgtdiscard++;
2555 		return;
2556 	}
2557 
2558 	/* make sure all mandatory fixed fields are present */
2559 	if (m->m_len < sizeof(*wh) + 6) {
2560 		DPRINTF(("frame too short\n"));
2561 		return;
2562 	}
2563 	wh = mtod(m, struct ieee80211_frame *);
2564 	frm = (const u_int8_t *)&wh[1];
2565 	efrm = mtod(m, u_int8_t *) + m->m_len;
2566 
2567 	capinfo = LE_READ_2(frm); frm += 2;
2568 	status =  LE_READ_2(frm); frm += 2;
2569 	if (status != IEEE80211_STATUS_SUCCESS) {
2570 		if (ifp->if_flags & IFF_DEBUG)
2571 			printf("%s: %sassociation failed (status %d)"
2572 			    " for %s\n", ifp->if_xname,
2573 			    reassoc ?  "re" : "",
2574 			    status, ether_sprintf((u_int8_t *)wh->i_addr3));
2575 		if (ni != ic->ic_bss)
2576 			ni->ni_fails++;
2577 		ic->ic_stats.is_rx_auth_fail++;
2578 		return;
2579 	}
2580 	associd = LE_READ_2(frm); frm += 2;
2581 
2582 	rates = xrates = edcaie = wmmie = htcaps = htop = NULL;
2583 	vhtcaps = vhtop = NULL;
2584 	while (frm + 2 <= efrm) {
2585 		if (frm + 2 + frm[1] > efrm) {
2586 			ic->ic_stats.is_rx_elem_toosmall++;
2587 			break;
2588 		}
2589 		switch (frm[0]) {
2590 		case IEEE80211_ELEMID_RATES:
2591 			rates = frm;
2592 			break;
2593 		case IEEE80211_ELEMID_XRATES:
2594 			xrates = frm;
2595 			break;
2596 		case IEEE80211_ELEMID_EDCAPARMS:
2597 			edcaie = frm;
2598 			break;
2599 		case IEEE80211_ELEMID_HTCAPS:
2600 			htcaps = frm;
2601 			break;
2602 		case IEEE80211_ELEMID_HTOP:
2603 			htop = frm;
2604 			break;
2605 		case IEEE80211_ELEMID_VHTCAPS:
2606 			vhtcaps = frm;
2607 			break;
2608 		case IEEE80211_ELEMID_VHTOP:
2609 			vhtop = frm;
2610 			break;
2611 		case IEEE80211_ELEMID_VENDOR:
2612 			if (frm[1] < 4) {
2613 				ic->ic_stats.is_rx_elem_toosmall++;
2614 				break;
2615 			}
2616 			if (memcmp(frm + 2, MICROSOFT_OUI, 3) == 0) {
2617 				if (frm[1] >= 5 && frm[5] == 2 && frm[6] == 1)
2618 					wmmie = frm;
2619 			}
2620 			break;
2621 		}
2622 		frm += 2 + frm[1];
2623 	}
2624 	/* supported rates element is mandatory */
2625 	if (rates == NULL || rates[1] > IEEE80211_RATE_MAXSIZE) {
2626 		DPRINTF(("invalid supported rates element\n"));
2627 		return;
2628 	}
2629 	rate = ieee80211_setup_rates(ic, ni, rates, xrates,
2630 	    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE | IEEE80211_F_DONEGO |
2631 	    IEEE80211_F_DODEL);
2632 	if (rate & IEEE80211_RATE_BASIC) {
2633 		DPRINTF(("rate mismatch for %s\n",
2634 		    ether_sprintf((u_int8_t *)wh->i_addr2)));
2635 		ic->ic_stats.is_rx_assoc_norate++;
2636 		return;
2637 	}
2638 	ni->ni_capinfo = capinfo;
2639 	ni->ni_associd = associd;
2640 	if (edcaie != NULL || wmmie != NULL) {
2641 		/* force update of EDCA parameters */
2642 		ic->ic_edca_updtcount = -1;
2643 
2644 		if ((edcaie != NULL &&
2645 		     ieee80211_parse_edca_params(ic, edcaie) == 0) ||
2646 		    (wmmie != NULL &&
2647 		     ieee80211_parse_wmm_params(ic, wmmie) == 0))
2648 			ni->ni_flags |= IEEE80211_NODE_QOS;
2649 		else	/* for Reassociation */
2650 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
2651 	}
2652 	if (htcaps)
2653 		ieee80211_setup_htcaps(ni, htcaps + 2, htcaps[1]);
2654 	if (htop)
2655 		ieee80211_setup_htop(ni, htop + 2, htop[1], 0);
2656 	ieee80211_ht_negotiate(ic, ni);
2657 
2658 	if (htcaps && vhtcaps && IEEE80211_IS_CHAN_5GHZ(ni->ni_chan)) {
2659 		ieee80211_setup_vhtcaps(ni, vhtcaps + 2, vhtcaps[1]);
2660 		if (vhtop && !ieee80211_setup_vhtop(ni, vhtop + 2, vhtop[1], 1))
2661 			vhtop = NULL; /* invalid VHTOP */
2662 	}
2663 	ieee80211_vht_negotiate(ic, ni);
2664 
2665 	/* Hop into 11n/11ac modes after associating to a HT/VHT AP. */
2666 	if (ni->ni_flags & IEEE80211_NODE_VHT)
2667 		ieee80211_setmode(ic, IEEE80211_MODE_11AC);
2668 	else if (ni->ni_flags & IEEE80211_NODE_HT)
2669 		ieee80211_setmode(ic, IEEE80211_MODE_11N);
2670 	else
2671 		ieee80211_setmode(ic, ieee80211_chan2mode(ic, ni->ni_chan));
2672 	/*
2673 	 * Reset the erp state (mostly the slot time) now that
2674 	 * our operating mode has been nailed down.
2675 	 */
2676 	ieee80211_reset_erp(ic);
2677 
2678 	/*
2679 	 * Configure state now that we are associated.
2680 	 */
2681 	if (ic->ic_curmode == IEEE80211_MODE_11A ||
2682 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE))
2683 		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2684 	else
2685 		ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2686 
2687 	ieee80211_set_shortslottime(ic,
2688 	    ic->ic_curmode == IEEE80211_MODE_11A ||
2689 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME));
2690 	/*
2691 	 * Honor ERP protection.
2692 	 */
2693 	if ((ic->ic_curmode == IEEE80211_MODE_11G ||
2694 	    (ic->ic_curmode == IEEE80211_MODE_11N &&
2695 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))) &&
2696 	    (ni->ni_erp & IEEE80211_ERP_USE_PROTECTION))
2697 		ic->ic_flags |= IEEE80211_F_USEPROT;
2698 	else
2699 		ic->ic_flags &= ~IEEE80211_F_USEPROT;
2700 	/*
2701 	 * If not an RSNA, mark the port as valid, otherwise wait for
2702 	 * 802.1X authentication and 4-way handshake to complete..
2703 	 */
2704 	if (ic->ic_flags & IEEE80211_F_RSNON) {
2705 		/* XXX ic->ic_mgt_timer = 5; */
2706 		ni->ni_rsn_supp_state = RSNA_SUPP_PTKSTART;
2707 	} else if (ic->ic_flags & IEEE80211_F_WEPON)
2708 		ni->ni_flags |= IEEE80211_NODE_TXRXPROT;
2709 
2710 	ieee80211_new_state(ic, IEEE80211_S_RUN,
2711 	    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2712 }
2713 
2714 /*-
2715  * Deauthentication frame format:
2716  * [2] Reason code
2717  */
2718 void
2719 ieee80211_recv_deauth(struct ieee80211com *ic, struct mbuf *m,
2720     struct ieee80211_node *ni)
2721 {
2722 	const struct ieee80211_frame *wh;
2723 	const u_int8_t *frm;
2724 	u_int16_t reason;
2725 
2726 	/* make sure all mandatory fixed fields are present */
2727 	if (m->m_len < sizeof(*wh) + 2) {
2728 		DPRINTF(("frame too short\n"));
2729 		return;
2730 	}
2731 	wh = mtod(m, struct ieee80211_frame *);
2732 	frm = (const u_int8_t *)&wh[1];
2733 
2734 	reason = LE_READ_2(frm);
2735 
2736 	ic->ic_stats.is_rx_deauth++;
2737 	switch (ic->ic_opmode) {
2738 	case IEEE80211_M_STA: {
2739 		int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
2740 		    ic->ic_state == IEEE80211_S_RUN);
2741 		int stay_auth = ((ic->ic_userflags & IEEE80211_F_STAYAUTH) &&
2742 		    ic->ic_state >= IEEE80211_S_AUTH);
2743 		if (!(bgscan || stay_auth))
2744 			ieee80211_new_state(ic, IEEE80211_S_AUTH,
2745 			    IEEE80211_FC0_SUBTYPE_DEAUTH);
2746 		}
2747 		break;
2748 #ifndef IEEE80211_STA_ONLY
2749 	case IEEE80211_M_HOSTAP:
2750 		if (ni != ic->ic_bss) {
2751 			int stay_auth =
2752 			    ((ic->ic_userflags & IEEE80211_F_STAYAUTH) &&
2753 			    (ni->ni_state == IEEE80211_STA_AUTH ||
2754 			    ni->ni_state == IEEE80211_STA_ASSOC));
2755 			if (ic->ic_if.if_flags & IFF_DEBUG)
2756 				printf("%s: station %s deauthenticated "
2757 				    "by peer (reason %d)\n",
2758 				    ic->ic_if.if_xname,
2759 				    ether_sprintf(ni->ni_macaddr),
2760 				    reason);
2761 			if (!stay_auth)
2762 				ieee80211_node_leave(ic, ni);
2763 		}
2764 		break;
2765 #endif
2766 	default:
2767 		break;
2768 	}
2769 }
2770 
2771 /*-
2772  * Disassociation frame format:
2773  * [2] Reason code
2774  */
2775 void
2776 ieee80211_recv_disassoc(struct ieee80211com *ic, struct mbuf *m,
2777     struct ieee80211_node *ni)
2778 {
2779 	const struct ieee80211_frame *wh;
2780 	const u_int8_t *frm;
2781 	u_int16_t reason;
2782 
2783 	/* make sure all mandatory fixed fields are present */
2784 	if (m->m_len < sizeof(*wh) + 2) {
2785 		DPRINTF(("frame too short\n"));
2786 		return;
2787 	}
2788 	wh = mtod(m, struct ieee80211_frame *);
2789 	frm = (const u_int8_t *)&wh[1];
2790 
2791 	reason = LE_READ_2(frm);
2792 
2793 	ic->ic_stats.is_rx_disassoc++;
2794 	switch (ic->ic_opmode) {
2795 	case IEEE80211_M_STA: {
2796 		int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
2797 		    ic->ic_state == IEEE80211_S_RUN);
2798 		if (!bgscan) /* ignore disassoc during bgscan */
2799 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
2800 			    IEEE80211_FC0_SUBTYPE_DISASSOC);
2801 		}
2802 		break;
2803 #ifndef IEEE80211_STA_ONLY
2804 	case IEEE80211_M_HOSTAP:
2805 		if (ni != ic->ic_bss) {
2806 			if (ic->ic_if.if_flags & IFF_DEBUG)
2807 				printf("%s: station %s disassociated "
2808 				    "by peer (reason %d)\n",
2809 				    ic->ic_if.if_xname,
2810 				    ether_sprintf(ni->ni_macaddr),
2811 				    reason);
2812 			ieee80211_node_leave(ic, ni);
2813 		}
2814 		break;
2815 #endif
2816 	default:
2817 		break;
2818 	}
2819 }
2820 
2821 /*-
2822  * ADDBA Request frame format:
2823  * [1] Category
2824  * [1] Action
2825  * [1] Dialog Token
2826  * [2] Block Ack Parameter Set
2827  * [2] Block Ack Timeout Value
2828  * [2] Block Ack Starting Sequence Control
2829  */
2830 void
2831 ieee80211_recv_addba_req(struct ieee80211com *ic, struct mbuf *m,
2832     struct ieee80211_node *ni)
2833 {
2834 	const struct ieee80211_frame *wh;
2835 	const u_int8_t *frm;
2836 	struct ieee80211_rx_ba *ba;
2837 	u_int16_t params, ssn, bufsz, timeout;
2838 	u_int8_t token, tid;
2839 	int err = 0;
2840 
2841 	if (!(ni->ni_flags & IEEE80211_NODE_HT)) {
2842 		DPRINTF(("received ADDBA req from non-HT STA %s\n",
2843 		    ether_sprintf(ni->ni_macaddr)));
2844 		return;
2845 	}
2846 	if (m->m_len < sizeof(*wh) + 9) {
2847 		DPRINTF(("frame too short\n"));
2848 		return;
2849 	}
2850 	/* MLME-ADDBA.indication */
2851 	wh = mtod(m, struct ieee80211_frame *);
2852 	frm = (const u_int8_t *)&wh[1];
2853 
2854 	token = frm[2];
2855 	params = LE_READ_2(&frm[3]);
2856 	tid = ((params & IEEE80211_ADDBA_TID_MASK) >>
2857 	    IEEE80211_ADDBA_TID_SHIFT);
2858 	bufsz = (params & IEEE80211_ADDBA_BUFSZ_MASK) >>
2859 	    IEEE80211_ADDBA_BUFSZ_SHIFT;
2860 	timeout = LE_READ_2(&frm[5]);
2861 	ssn = LE_READ_2(&frm[7]) >> 4;
2862 
2863 	ba = &ni->ni_rx_ba[tid];
2864 	/* The driver is still processing an ADDBA request for this tid. */
2865 	if (ba->ba_state == IEEE80211_BA_REQUESTED)
2866 		return;
2867 	/* If we are in the process of roaming between APs, ignore. */
2868 	if ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
2869 	    (ic->ic_xflags & IEEE80211_F_TX_MGMT_ONLY))
2870 		return;
2871 	/* check if we already have a Block Ack agreement for this RA/TID */
2872 	if (ba->ba_state == IEEE80211_BA_AGREED) {
2873 		/* XXX should we update the timeout value? */
2874 		/* reset Block Ack inactivity timer */
2875 		if (ba->ba_timeout_val != 0)
2876 			timeout_add_usec(&ba->ba_to, ba->ba_timeout_val);
2877 
2878 		/* check if it's a Protected Block Ack agreement */
2879 		if (!(ni->ni_flags & IEEE80211_NODE_MFP) ||
2880 		    !(ni->ni_rsncaps & IEEE80211_RSNCAP_PBAC))
2881 			return;	/* not a PBAC, ignore */
2882 
2883 		/* PBAC: treat the ADDBA Request like a BlockAckReq */
2884 		if (SEQ_LT(ba->ba_winstart, ssn)) {
2885 			struct mbuf_list ml = MBUF_LIST_INITIALIZER();
2886 			ieee80211_ba_move_window(ic, ni, tid, ssn, &ml);
2887 			if_input(&ic->ic_if, &ml);
2888 		}
2889 		return;
2890 	}
2891 
2892 	/* if PBAC required but RA does not support it, refuse request */
2893 	if ((ic->ic_flags & IEEE80211_F_PBAR) &&
2894 	    (!(ni->ni_flags & IEEE80211_NODE_MFP) ||
2895 	     !(ni->ni_rsncaps & IEEE80211_RSNCAP_PBAC)))
2896 		goto refuse;
2897 	/*
2898 	 * If the TID for which the Block Ack agreement is requested is
2899 	 * configured with a no-ACK policy, refuse the agreement.
2900 	 */
2901 	if (ic->ic_tid_noack & (1 << tid))
2902 		goto refuse;
2903 
2904 	/* check that we support the requested Block Ack Policy */
2905 	if (!(ic->ic_htcaps & IEEE80211_HTCAP_DELAYEDBA) &&
2906 	    !(params & IEEE80211_ADDBA_BA_POLICY))
2907 		goto refuse;
2908 
2909 	/* setup Block Ack agreement */
2910 	ba->ba_state = IEEE80211_BA_REQUESTED;
2911 	ba->ba_timeout_val = timeout * IEEE80211_DUR_TU;
2912 	ba->ba_ni = ni;
2913 	ba->ba_token = token;
2914 	timeout_set(&ba->ba_to, ieee80211_rx_ba_timeout, ba);
2915 	timeout_set(&ba->ba_gap_to, ieee80211_input_ba_gap_timeout, ba);
2916 	ba->ba_gapwait = 0;
2917 	ba->ba_winsize = bufsz;
2918 	if (ba->ba_winsize == 0 || ba->ba_winsize > IEEE80211_BA_MAX_WINSZ)
2919 		ba->ba_winsize = IEEE80211_BA_MAX_WINSZ;
2920 	ba->ba_params = (params & IEEE80211_ADDBA_BA_POLICY);
2921 	ba->ba_params |= ((ba->ba_winsize << IEEE80211_ADDBA_BUFSZ_SHIFT) |
2922 	    (tid << IEEE80211_ADDBA_TID_SHIFT));
2923 	ba->ba_params |= IEEE80211_ADDBA_AMSDU;
2924 	ba->ba_winstart = ssn;
2925 	ba->ba_winend = (ba->ba_winstart + ba->ba_winsize - 1) & 0xfff;
2926 	/* allocate and setup our reordering buffer */
2927 	ba->ba_buf = malloc(IEEE80211_BA_MAX_WINSZ * sizeof(*ba->ba_buf),
2928 	    M_DEVBUF, M_NOWAIT | M_ZERO);
2929 	if (ba->ba_buf == NULL)
2930 		goto refuse;
2931 
2932 	ba->ba_head = 0;
2933 
2934 	/* notify drivers of this new Block Ack agreement */
2935 	if (ic->ic_ampdu_rx_start != NULL)
2936 		err = ic->ic_ampdu_rx_start(ic, ni, tid);
2937 	if (err == EBUSY) {
2938 		/* driver will accept or refuse agreement when done */
2939 		return;
2940 	} else if (err) {
2941 		/* driver failed to setup, rollback */
2942 		ieee80211_addba_req_refuse(ic, ni, tid);
2943 	} else
2944 		ieee80211_addba_req_accept(ic, ni, tid);
2945 	return;
2946 
2947  refuse:
2948 	/* MLME-ADDBA.response */
2949 	IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
2950 	    IEEE80211_ACTION_ADDBA_RESP,
2951 	    IEEE80211_STATUS_REFUSED << 16 | token << 8 | tid);
2952 }
2953 
2954 void
2955 ieee80211_addba_req_accept(struct ieee80211com *ic, struct ieee80211_node *ni,
2956     uint8_t tid)
2957 {
2958 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
2959 
2960 	ba->ba_state = IEEE80211_BA_AGREED;
2961 	ic->ic_stats.is_ht_rx_ba_agreements++;
2962 	/* start Block Ack inactivity timer */
2963 	if (ba->ba_timeout_val != 0)
2964 		timeout_add_usec(&ba->ba_to, ba->ba_timeout_val);
2965 
2966 	/* MLME-ADDBA.response */
2967 	IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
2968 	    IEEE80211_ACTION_ADDBA_RESP,
2969 	    IEEE80211_STATUS_SUCCESS << 16 | ba->ba_token << 8 | tid);
2970 }
2971 
2972 void
2973 ieee80211_addba_req_refuse(struct ieee80211com *ic, struct ieee80211_node *ni,
2974     uint8_t tid)
2975 {
2976 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
2977 
2978 	free(ba->ba_buf, M_DEVBUF,
2979 	    IEEE80211_BA_MAX_WINSZ * sizeof(*ba->ba_buf));
2980 	ba->ba_buf = NULL;
2981 	ba->ba_state = IEEE80211_BA_INIT;
2982 
2983 	/* MLME-ADDBA.response */
2984 	IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
2985 	    IEEE80211_ACTION_ADDBA_RESP,
2986 	    IEEE80211_STATUS_REFUSED << 16 | ba->ba_token << 8 | tid);
2987 }
2988 
2989 /*-
2990  * ADDBA Response frame format:
2991  * [1] Category
2992  * [1] Action
2993  * [1] Dialog Token
2994  * [2] Status Code
2995  * [2] Block Ack Parameter Set
2996  * [2] Block Ack Timeout Value
2997  */
2998 void
2999 ieee80211_recv_addba_resp(struct ieee80211com *ic, struct mbuf *m,
3000     struct ieee80211_node *ni)
3001 {
3002 	const struct ieee80211_frame *wh;
3003 	const u_int8_t *frm;
3004 	struct ieee80211_tx_ba *ba;
3005 	u_int16_t status, params, bufsz, timeout;
3006 	u_int8_t token, tid;
3007 	int err = 0;
3008 
3009 	if (m->m_len < sizeof(*wh) + 9) {
3010 		DPRINTF(("frame too short\n"));
3011 		return;
3012 	}
3013 	wh = mtod(m, struct ieee80211_frame *);
3014 	frm = (const u_int8_t *)&wh[1];
3015 
3016 	token = frm[2];
3017 	status = LE_READ_2(&frm[3]);
3018 	params = LE_READ_2(&frm[5]);
3019 	tid = (params >> 2) & 0xf;
3020 	bufsz = (params >> 6) & 0x3ff;
3021 	timeout = LE_READ_2(&frm[7]);
3022 
3023 	DPRINTF(("received ADDBA resp from %s, TID %d, status %d\n",
3024 	    ether_sprintf(ni->ni_macaddr), tid, status));
3025 
3026 	/*
3027 	 * Ignore if no ADDBA request has been sent for this RA/TID or
3028 	 * if we already have a Block Ack agreement.
3029 	 */
3030 	ba = &ni->ni_tx_ba[tid];
3031 	if (ba->ba_state != IEEE80211_BA_REQUESTED) {
3032 		DPRINTF(("no matching ADDBA req found\n"));
3033 		return;
3034 	}
3035 	if (token != ba->ba_token) {
3036 		DPRINTF(("ignoring ADDBA resp from %s: token %x!=%x\n",
3037 		    ether_sprintf(ni->ni_macaddr), token, ba->ba_token));
3038 		return;
3039 	}
3040 	/* we got an ADDBA Response matching our request, stop timeout */
3041 	timeout_del(&ba->ba_to);
3042 
3043 	if (status != IEEE80211_STATUS_SUCCESS) {
3044 		if (ni->ni_addba_req_intval[tid] <
3045 		    IEEE80211_ADDBA_REQ_INTVAL_MAX)
3046 			ni->ni_addba_req_intval[tid]++;
3047 
3048 		ieee80211_addba_resp_refuse(ic, ni, tid, status);
3049 
3050 		/*
3051 		 * In case the peer believes there is an existing
3052 		 * block ack agreement with us, try to delete it.
3053 		 */
3054 		IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
3055 		    IEEE80211_ACTION_DELBA,
3056 		    IEEE80211_REASON_SETUP_REQUIRED << 16 | 1 << 8 | tid);
3057 		return;
3058 	}
3059 
3060 	/* notify drivers of this new Block Ack agreement */
3061 	if (ic->ic_ampdu_tx_start != NULL)
3062 		err = ic->ic_ampdu_tx_start(ic, ni, tid);
3063 
3064 	if (err == EBUSY) {
3065 		/* driver will accept or refuse agreement when done */
3066 		return;
3067 	} else if (err) {
3068 		/* driver failed to setup, rollback */
3069 		ieee80211_addba_resp_refuse(ic, ni, tid,
3070 		    IEEE80211_STATUS_UNSPECIFIED);
3071 	} else
3072 		ieee80211_addba_resp_accept(ic, ni, tid);
3073 }
3074 
3075 void
3076 ieee80211_addba_resp_accept(struct ieee80211com *ic,
3077     struct ieee80211_node *ni, uint8_t tid)
3078 {
3079 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
3080 
3081 	/* MLME-ADDBA.confirm(Success) */
3082 	ba->ba_state = IEEE80211_BA_AGREED;
3083 	ic->ic_stats.is_ht_tx_ba_agreements++;
3084 
3085 	/* Reset ADDBA request interval. */
3086 	ni->ni_addba_req_intval[tid] = 1;
3087 
3088 	ni->ni_qos_txseqs[tid] = ba->ba_winstart;
3089 
3090 	/* start Block Ack inactivity timeout */
3091 	if (ba->ba_timeout_val != 0)
3092 		timeout_add_usec(&ba->ba_to, ba->ba_timeout_val);
3093 }
3094 
3095 void
3096 ieee80211_addba_resp_refuse(struct ieee80211com *ic,
3097     struct ieee80211_node *ni, uint8_t tid, uint16_t status)
3098 {
3099 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
3100 
3101 	/* MLME-ADDBA.confirm(Failure) */
3102 	ba->ba_state = IEEE80211_BA_INIT;
3103 }
3104 
3105 /*-
3106  * DELBA frame format:
3107  * [1] Category
3108  * [1] Action
3109  * [2] DELBA Parameter Set
3110  * [2] Reason Code
3111  */
3112 void
3113 ieee80211_recv_delba(struct ieee80211com *ic, struct mbuf *m,
3114     struct ieee80211_node *ni)
3115 {
3116 	const struct ieee80211_frame *wh;
3117 	const u_int8_t *frm;
3118 	u_int16_t params, reason;
3119 	u_int8_t tid;
3120 	int i;
3121 
3122 	if (m->m_len < sizeof(*wh) + 6) {
3123 		DPRINTF(("frame too short\n"));
3124 		return;
3125 	}
3126 	wh = mtod(m, struct ieee80211_frame *);
3127 	frm = (const u_int8_t *)&wh[1];
3128 
3129 	params = LE_READ_2(&frm[2]);
3130 	reason = LE_READ_2(&frm[4]);
3131 	tid = params >> 12;
3132 
3133 	DPRINTF(("received DELBA from %s, TID %d, reason %d\n",
3134 	    ether_sprintf(ni->ni_macaddr), tid, reason));
3135 
3136 	if (params & IEEE80211_DELBA_INITIATOR) {
3137 		/* MLME-DELBA.indication(Originator) */
3138 		struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
3139 
3140 		if (ba->ba_state != IEEE80211_BA_AGREED) {
3141 			DPRINTF(("no matching Block Ack agreement\n"));
3142 			return;
3143 		}
3144 		/* notify drivers of the end of the Block Ack agreement */
3145 		if (ic->ic_ampdu_rx_stop != NULL)
3146 			ic->ic_ampdu_rx_stop(ic, ni, tid);
3147 
3148 		ba->ba_state = IEEE80211_BA_INIT;
3149 		/* stop Block Ack inactivity timer */
3150 		timeout_del(&ba->ba_to);
3151 		timeout_del(&ba->ba_gap_to);
3152 		ba->ba_gapwait = 0;
3153 
3154 		if (ba->ba_buf != NULL) {
3155 			/* free all MSDUs stored in reordering buffer */
3156 			for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
3157 				m_freem(ba->ba_buf[i].m);
3158 			/* free reordering buffer */
3159 			free(ba->ba_buf, M_DEVBUF,
3160 			    IEEE80211_BA_MAX_WINSZ * sizeof(*ba->ba_buf));
3161 			ba->ba_buf = NULL;
3162 		}
3163 	} else {
3164 		/* MLME-DELBA.indication(Recipient) */
3165 		struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
3166 
3167 		if (ba->ba_state != IEEE80211_BA_AGREED) {
3168 			DPRINTF(("no matching Block Ack agreement\n"));
3169 			return;
3170 		}
3171 		/* notify drivers of the end of the Block Ack agreement */
3172 		if (ic->ic_ampdu_tx_stop != NULL)
3173 			ic->ic_ampdu_tx_stop(ic, ni, tid);
3174 
3175 		ba->ba_state = IEEE80211_BA_INIT;
3176 		/* stop Block Ack inactivity timer */
3177 		timeout_del(&ba->ba_to);
3178 	}
3179 }
3180 
3181 /*-
3182  * SA Query Request frame format:
3183  * [1] Category
3184  * [1] Action
3185  * [2] Transaction Identifier
3186  */
3187 void
3188 ieee80211_recv_sa_query_req(struct ieee80211com *ic, struct mbuf *m,
3189     struct ieee80211_node *ni)
3190 {
3191 	const struct ieee80211_frame *wh;
3192 	const u_int8_t *frm;
3193 
3194 	if (ic->ic_opmode != IEEE80211_M_STA ||
3195 	    !(ni->ni_flags & IEEE80211_NODE_MFP)) {
3196 		DPRINTF(("unexpected SA Query req from %s\n",
3197 		    ether_sprintf(ni->ni_macaddr)));
3198 		return;
3199 	}
3200 	if (m->m_len < sizeof(*wh) + 4) {
3201 		DPRINTF(("frame too short\n"));
3202 		return;
3203 	}
3204 	wh = mtod(m, struct ieee80211_frame *);
3205 	frm = (const u_int8_t *)&wh[1];
3206 
3207 	/* MLME-SAQuery.indication */
3208 
3209 	/* save Transaction Identifier for SA Query Response */
3210 	ni->ni_sa_query_trid = LE_READ_2(&frm[2]);
3211 
3212 	/* MLME-SAQuery.response */
3213 	IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_SA_QUERY,
3214 	    IEEE80211_ACTION_SA_QUERY_RESP, 0);
3215 }
3216 
3217 #ifndef IEEE80211_STA_ONLY
3218 /*-
3219  * SA Query Response frame format:
3220  * [1] Category
3221  * [1] Action
3222  * [2] Transaction Identifier
3223  */
3224 void
3225 ieee80211_recv_sa_query_resp(struct ieee80211com *ic, struct mbuf *m,
3226     struct ieee80211_node *ni)
3227 {
3228 	const struct ieee80211_frame *wh;
3229 	const u_int8_t *frm;
3230 
3231 	/* ignore if we're not engaged in an SA Query with that STA */
3232 	if (!(ni->ni_flags & IEEE80211_NODE_SA_QUERY)) {
3233 		DPRINTF(("unexpected SA Query resp from %s\n",
3234 		    ether_sprintf(ni->ni_macaddr)));
3235 		return;
3236 	}
3237 	if (m->m_len < sizeof(*wh) + 4) {
3238 		DPRINTF(("frame too short\n"));
3239 		return;
3240 	}
3241 	wh = mtod(m, struct ieee80211_frame *);
3242 	frm = (const u_int8_t *)&wh[1];
3243 
3244 	/* check that Transaction Identifier matches */
3245 	if (ni->ni_sa_query_trid != LE_READ_2(&frm[2])) {
3246 		DPRINTF(("transaction identifier does not match\n"));
3247 		return;
3248 	}
3249 	/* MLME-SAQuery.confirm */
3250 	timeout_del(&ni->ni_sa_query_to);
3251 	ni->ni_flags &= ~IEEE80211_NODE_SA_QUERY;
3252 }
3253 #endif
3254 
3255 /*-
3256  * Action frame format:
3257  * [1] Category
3258  * [1] Action
3259  */
3260 void
3261 ieee80211_recv_action(struct ieee80211com *ic, struct mbuf *m,
3262     struct ieee80211_node *ni)
3263 {
3264 	const struct ieee80211_frame *wh;
3265 	const u_int8_t *frm;
3266 
3267 	if (m->m_len < sizeof(*wh) + 2) {
3268 		DPRINTF(("frame too short\n"));
3269 		return;
3270 	}
3271 	wh = mtod(m, struct ieee80211_frame *);
3272 	frm = (const u_int8_t *)&wh[1];
3273 
3274 	switch (frm[0]) {
3275 	case IEEE80211_CATEG_BA:
3276 		switch (frm[1]) {
3277 		case IEEE80211_ACTION_ADDBA_REQ:
3278 			ieee80211_recv_addba_req(ic, m, ni);
3279 			break;
3280 		case IEEE80211_ACTION_ADDBA_RESP:
3281 			ieee80211_recv_addba_resp(ic, m, ni);
3282 			break;
3283 		case IEEE80211_ACTION_DELBA:
3284 			ieee80211_recv_delba(ic, m, ni);
3285 			break;
3286 		}
3287 		break;
3288 	case IEEE80211_CATEG_SA_QUERY:
3289 		switch (frm[1]) {
3290 		case IEEE80211_ACTION_SA_QUERY_REQ:
3291 			ieee80211_recv_sa_query_req(ic, m, ni);
3292 			break;
3293 #ifndef IEEE80211_STA_ONLY
3294 		case IEEE80211_ACTION_SA_QUERY_RESP:
3295 			ieee80211_recv_sa_query_resp(ic, m, ni);
3296 			break;
3297 #endif
3298 		}
3299 		break;
3300 	default:
3301 		DPRINTF(("action frame category %d not handled\n", frm[0]));
3302 		break;
3303 	}
3304 }
3305 
3306 void
3307 ieee80211_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
3308     struct ieee80211_node *ni, struct ieee80211_rxinfo *rxi, int subtype)
3309 {
3310 	switch (subtype) {
3311 	case IEEE80211_FC0_SUBTYPE_BEACON:
3312 		ieee80211_recv_probe_resp(ic, m, ni, rxi, 0);
3313 		break;
3314 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3315 		ieee80211_recv_probe_resp(ic, m, ni, rxi, 1);
3316 		break;
3317 #ifndef IEEE80211_STA_ONLY
3318 	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
3319 		ieee80211_recv_probe_req(ic, m, ni, rxi);
3320 		break;
3321 #endif
3322 	case IEEE80211_FC0_SUBTYPE_AUTH:
3323 		ieee80211_recv_auth(ic, m, ni, rxi);
3324 		break;
3325 #ifndef IEEE80211_STA_ONLY
3326 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
3327 		ieee80211_recv_assoc_req(ic, m, ni, rxi, 0);
3328 		break;
3329 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
3330 		ieee80211_recv_assoc_req(ic, m, ni, rxi, 1);
3331 		break;
3332 #endif
3333 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
3334 		ieee80211_recv_assoc_resp(ic, m, ni, 0);
3335 		break;
3336 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
3337 		ieee80211_recv_assoc_resp(ic, m, ni, 1);
3338 		break;
3339 	case IEEE80211_FC0_SUBTYPE_DEAUTH:
3340 		ieee80211_recv_deauth(ic, m, ni);
3341 		break;
3342 	case IEEE80211_FC0_SUBTYPE_DISASSOC:
3343 		ieee80211_recv_disassoc(ic, m, ni);
3344 		break;
3345 	case IEEE80211_FC0_SUBTYPE_ACTION:
3346 		ieee80211_recv_action(ic, m, ni);
3347 		break;
3348 	default:
3349 		DPRINTF(("mgmt frame with subtype 0x%x not handled\n",
3350 		    subtype));
3351 		ic->ic_stats.is_rx_badsubtype++;
3352 		break;
3353 	}
3354 }
3355 
3356 #ifndef IEEE80211_STA_ONLY
3357 /*
3358  * Process an incoming PS-Poll control frame (see 11.2).
3359  */
3360 void
3361 ieee80211_recv_pspoll(struct ieee80211com *ic, struct mbuf *m,
3362     struct ieee80211_node *ni)
3363 {
3364 	struct ifnet *ifp = &ic->ic_if;
3365 	struct ieee80211_frame_pspoll *psp;
3366 	struct ieee80211_frame *wh;
3367 	u_int16_t aid;
3368 
3369 	if (ic->ic_opmode != IEEE80211_M_HOSTAP ||
3370 	    !(ic->ic_caps & IEEE80211_C_APPMGT) ||
3371 	    ni->ni_state != IEEE80211_STA_ASSOC)
3372 		return;
3373 
3374 	if (m->m_len < sizeof(*psp)) {
3375 		DPRINTF(("frame too short, len %u\n", m->m_len));
3376 		ic->ic_stats.is_rx_tooshort++;
3377 		return;
3378 	}
3379 	psp = mtod(m, struct ieee80211_frame_pspoll *);
3380 	if (!IEEE80211_ADDR_EQ(psp->i_bssid, ic->ic_bss->ni_bssid)) {
3381 		DPRINTF(("discard pspoll frame to BSS %s\n",
3382 		    ether_sprintf(psp->i_bssid)));
3383 		ic->ic_stats.is_rx_wrongbss++;
3384 		return;
3385 	}
3386 	aid = letoh16(*(u_int16_t *)psp->i_aid);
3387 	if (aid != ni->ni_associd) {
3388 		DPRINTF(("invalid pspoll aid %x from %s\n", aid,
3389 		    ether_sprintf(psp->i_ta)));
3390 		return;
3391 	}
3392 
3393 	/* take the first queued frame and put it out.. */
3394 	m = mq_dequeue(&ni->ni_savedq);
3395 	if (m == NULL)
3396 		return;
3397 	if (mq_empty(&ni->ni_savedq)) {
3398 		/* last queued frame, turn off the TIM bit */
3399 		(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
3400 	} else {
3401 		/* more queued frames, set the more data bit */
3402 		wh = mtod(m, struct ieee80211_frame *);
3403 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
3404 	}
3405 	mq_enqueue(&ic->ic_pwrsaveq, m);
3406 	if_start(ifp);
3407 }
3408 #endif	/* IEEE80211_STA_ONLY */
3409 
3410 /*
3411  * Process an incoming BlockAckReq control frame (see 7.2.1.7).
3412  */
3413 void
3414 ieee80211_recv_bar(struct ieee80211com *ic, struct mbuf *m,
3415     struct ieee80211_node *ni)
3416 {
3417 	const struct ieee80211_frame_min *wh;
3418 	const u_int8_t *frm;
3419 	u_int16_t ctl, ssn;
3420 	u_int8_t tid, ntids;
3421 
3422 	if (!(ni->ni_flags & IEEE80211_NODE_HT)) {
3423 		DPRINTF(("received BlockAckReq from non-HT STA %s\n",
3424 		    ether_sprintf(ni->ni_macaddr)));
3425 		return;
3426 	}
3427 	if (m->m_len < sizeof(*wh) + 4) {
3428 		DPRINTF(("frame too short\n"));
3429 		return;
3430 	}
3431 	wh = mtod(m, struct ieee80211_frame_min *);
3432 	frm = (const u_int8_t *)&wh[1];
3433 
3434 	/* read BlockAckReq Control field */
3435 	ctl = LE_READ_2(&frm[0]);
3436 	tid = ctl >> 12;
3437 
3438 	/* determine BlockAckReq frame variant */
3439 	if (ctl & IEEE80211_BA_MULTI_TID) {
3440 		/* Multi-TID BlockAckReq variant (PSMP only) */
3441 		ntids = tid + 1;
3442 
3443 		if (m->m_len < sizeof(*wh) + 2 + 4 * ntids) {
3444 			DPRINTF(("MTBAR frame too short\n"));
3445 			return;
3446 		}
3447 		frm += 2;	/* skip BlockAckReq Control field */
3448 		while (ntids-- > 0) {
3449 			/* read MTBAR Information field */
3450 			tid = LE_READ_2(&frm[0]) >> 12;
3451 			ssn = LE_READ_2(&frm[2]) >> 4;
3452 			ieee80211_bar_tid(ic, ni, tid, ssn);
3453 			frm += 4;
3454 		}
3455 	} else {
3456 		/* Basic or Compressed BlockAckReq variants */
3457 		ssn = LE_READ_2(&frm[2]) >> 4;
3458 		ieee80211_bar_tid(ic, ni, tid, ssn);
3459 	}
3460 }
3461 
3462 /*
3463  * Process a BlockAckReq for a specific TID (see 9.10.7.6.3).
3464  * This is the common back-end for all BlockAckReq frame variants.
3465  */
3466 void
3467 ieee80211_bar_tid(struct ieee80211com *ic, struct ieee80211_node *ni,
3468     u_int8_t tid, u_int16_t ssn)
3469 {
3470 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
3471 
3472 	/* check if we have a Block Ack agreement for RA/TID */
3473 	if (ba->ba_state != IEEE80211_BA_AGREED) {
3474 		/* XXX not sure in PBAC case */
3475 		/* send a DELBA with reason code UNKNOWN-BA */
3476 		IEEE80211_SEND_ACTION(ic, ni, IEEE80211_CATEG_BA,
3477 		    IEEE80211_ACTION_DELBA,
3478 		    IEEE80211_REASON_SETUP_REQUIRED << 16 | tid);
3479 		return;
3480 	}
3481 	/* check if it is a Protected Block Ack agreement */
3482 	if ((ni->ni_flags & IEEE80211_NODE_MFP) &&
3483 	    (ni->ni_rsncaps & IEEE80211_RSNCAP_PBAC)) {
3484 		/* ADDBA Requests must be used in PBAC case */
3485 		if (SEQ_LT(ssn, ba->ba_winstart) ||
3486 		    SEQ_LT(ba->ba_winend, ssn))
3487 			ic->ic_stats.is_pbac_errs++;
3488 		return;	/* PBAC, do not move window */
3489 	}
3490 	/* reset Block Ack inactivity timer */
3491 	if (ba->ba_timeout_val != 0)
3492 		timeout_add_usec(&ba->ba_to, ba->ba_timeout_val);
3493 
3494 	if (SEQ_LT(ba->ba_winstart, ssn)) {
3495 		struct mbuf_list ml = MBUF_LIST_INITIALIZER();
3496 		ieee80211_ba_move_window(ic, ni, tid, ssn, &ml);
3497 		if_input(&ic->ic_if, &ml);
3498 	}
3499 }
3500