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