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