xref: /netbsd-src/sys/net80211/ieee80211_input.c (revision 5b84b3983f71fd20a534cfa5d1556623a8aaa717)
1 /*	$NetBSD: ieee80211_input.c,v 1.45 2005/08/18 00:30:59 yamt Exp $	*/
2 /*-
3  * Copyright (c) 2001 Atsushi Onoe
4  * Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * Alternatively, this software may be distributed under the terms of the
19  * GNU General Public License ("GPL") version 2 as published by the Free
20  * Software Foundation.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 #ifdef __FreeBSD__
36 __FBSDID("$FreeBSD: src/sys/net80211/ieee80211_input.c,v 1.62 2005/07/11 03:00:20 sam Exp $");
37 #endif
38 #ifdef __NetBSD__
39 __KERNEL_RCSID(0, "$NetBSD: ieee80211_input.c,v 1.45 2005/08/18 00:30:59 yamt Exp $");
40 #endif
41 
42 #include "opt_inet.h"
43 
44 #ifdef __NetBSD__
45 #include "bpfilter.h"
46 #endif /* __NetBSD__ */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/mbuf.h>
51 #include <sys/malloc.h>
52 #include <sys/endian.h>
53 #include <sys/kernel.h>
54 
55 #include <sys/socket.h>
56 #include <sys/sockio.h>
57 #include <sys/endian.h>
58 #include <sys/errno.h>
59 #include <sys/proc.h>
60 #include <sys/sysctl.h>
61 
62 #include <net/if.h>
63 #include <net/if_media.h>
64 #include <net/if_arp.h>
65 #include <net/if_ether.h>
66 #include <net/if_llc.h>
67 
68 #include <net80211/ieee80211_netbsd.h>
69 #include <net80211/ieee80211_var.h>
70 
71 #if NBPFILTER > 0
72 #include <net/bpf.h>
73 #endif
74 
75 #ifdef INET
76 #include <netinet/in.h>
77 #include <net/if_ether.h>
78 #endif
79 
80 const struct timeval ieee80211_merge_print_intvl = {.tv_sec = 1, .tv_usec = 0};
81 
82 #ifdef IEEE80211_DEBUG
83 #include <machine/stdarg.h>
84 
85 /*
86  * Decide if a received management frame should be
87  * printed when debugging is enabled.  This filters some
88  * of the less interesting frames that come frequently
89  * (e.g. beacons).
90  */
91 static __inline int
92 doprint(struct ieee80211com *ic, int subtype)
93 {
94 	switch (subtype) {
95 	case IEEE80211_FC0_SUBTYPE_BEACON:
96 		return (ic->ic_flags & IEEE80211_F_SCAN);
97 	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
98 		return (ic->ic_opmode == IEEE80211_M_IBSS);
99 	}
100 	return 1;
101 }
102 
103 /*
104  * Emit a debug message about discarding a frame or information
105  * element.  One format is for extracting the mac address from
106  * the frame header; the other is for when a header is not
107  * available or otherwise appropriate.
108  */
109 #define	IEEE80211_DISCARD(_ic, _m, _wh, _type, _fmt, ...) do {		\
110 	if ((_ic)->ic_debug & (_m))					\
111 		ieee80211_discard_frame(_ic, _wh, _type, _fmt, __VA_ARGS__);\
112 } while (0)
113 #define	IEEE80211_DISCARD_IE(_ic, _m, _wh, _type, _fmt, ...) do {	\
114 	if ((_ic)->ic_debug & (_m))					\
115 		ieee80211_discard_ie(_ic, _wh, _type, _fmt, __VA_ARGS__);\
116 } while (0)
117 #define	IEEE80211_DISCARD_MAC(_ic, _m, _mac, _type, _fmt, ...) do {	\
118 	if ((_ic)->ic_debug & (_m))					\
119 		ieee80211_discard_mac(_ic, _mac, _type, _fmt, __VA_ARGS__);\
120 } while (0)
121 
122 static const u_int8_t *ieee80211_getbssid(struct ieee80211com *,
123 	const struct ieee80211_frame *);
124 static void ieee80211_discard_frame(struct ieee80211com *,
125 	const struct ieee80211_frame *, const char *type, const char *fmt, ...);
126 static void ieee80211_discard_ie(struct ieee80211com *,
127 	const struct ieee80211_frame *, const char *type, const char *fmt, ...);
128 static void ieee80211_discard_mac(struct ieee80211com *,
129 	const u_int8_t mac[IEEE80211_ADDR_LEN], const char *type,
130 	const char *fmt, ...);
131 #else
132 #define	IEEE80211_DISCARD(_ic, _m, _wh, _type, _fmt, ...)
133 #define	IEEE80211_DISCARD_IE(_ic, _m, _wh, _type, _fmt, ...)
134 #define	IEEE80211_DISCARD_MAC(_ic, _m, _mac, _type, _fmt, ...)
135 #endif /* IEEE80211_DEBUG */
136 
137 static struct mbuf *ieee80211_defrag(struct ieee80211com *,
138 	struct ieee80211_node *, struct mbuf *, int);
139 static struct mbuf *ieee80211_decap(struct ieee80211com *, struct mbuf *, int);
140 static void ieee80211_send_error(struct ieee80211com *, struct ieee80211_node *,
141 		const u_int8_t *mac, int subtype, int arg);
142 #ifndef IEEE80211_NO_HOSTAP
143 static void ieee80211_node_pwrsave(struct ieee80211_node *, int enable);
144 static void ieee80211_recv_pspoll(struct ieee80211com *,
145 	struct ieee80211_node *, struct mbuf *);
146 #endif /* !IEEE80211_NO_HOSTAP */
147 
148 /*
149  * Process a received frame.  The node associated with the sender
150  * should be supplied.  If nothing was found in the node table then
151  * the caller is assumed to supply a reference to ic_bss instead.
152  * The RSSI and a timestamp are also supplied.  The RSSI data is used
153  * during AP scanning to select a AP to associate with; it can have
154  * any units so long as values have consistent units and higher values
155  * mean ``better signal''.  The receive timestamp is currently not used
156  * by the 802.11 layer.
157  */
158 int
159 ieee80211_input(struct ieee80211com *ic, struct mbuf *m,
160 	struct ieee80211_node *ni, int rssi, u_int32_t rstamp)
161 {
162 #define	SEQ_LEQ(a,b)	((int)((a)-(b)) <= 0)
163 #define	HAS_SEQ(type)	((type & 0x4) == 0)
164 	struct ifnet *ifp = ic->ic_ifp;
165 	struct ieee80211_frame *wh;
166 	struct ieee80211_key *key;
167 	struct ether_header *eh;
168 	int hdrspace;
169 	u_int8_t dir, type, subtype;
170 	u_int8_t *bssid;
171 	u_int16_t rxseq;
172 	ALTQ_DECL(struct altq_pktattr pktattr;)
173 
174 	IASSERT(ni != NULL, ("null node"));
175 	ni->ni_inact = ni->ni_inact_reload;
176 
177 	/* trim CRC here so WEP can find its own CRC at the end of packet. */
178 	if (m->m_flags & M_HASFCS) {
179 		m_adj(m, -IEEE80211_CRC_LEN);
180 		m->m_flags &= ~M_HASFCS;
181 	}
182 	type = -1;			/* undefined */
183 	/*
184 	 * In monitor mode, send everything directly to bpf.
185 	 * XXX may want to include the CRC
186 	 */
187 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
188 		goto out;
189 
190 	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_min)) {
191 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_ANY,
192 		    ni->ni_macaddr, NULL,
193 		    "too short (1): len %u", m->m_pkthdr.len);
194 		ic->ic_stats.is_rx_tooshort++;
195 		goto out;
196 	}
197 	/*
198 	 * Bit of a cheat here, we use a pointer for a 3-address
199 	 * frame format but don't reference fields past outside
200 	 * ieee80211_frame_min w/o first validating the data is
201 	 * present.
202 	 */
203 	wh = mtod(m, struct ieee80211_frame *);
204 
205 	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
206 	    IEEE80211_FC0_VERSION_0) {
207 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_ANY,
208 		    ni->ni_macaddr, NULL, "wrong version %x", wh->i_fc[0]);
209 		ic->ic_stats.is_rx_badversion++;
210 		goto err;
211 	}
212 
213 	dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
214 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
215 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
216 	if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
217 		switch (ic->ic_opmode) {
218 		case IEEE80211_M_STA:
219 			bssid = wh->i_addr2;
220 			if (!IEEE80211_ADDR_EQ(bssid, ni->ni_bssid)) {
221 				/* not interested in */
222 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_INPUT,
223 				    bssid, NULL, "%s", "not to bss");
224 				ic->ic_stats.is_rx_wrongbss++;
225 				goto out;
226 			}
227 			break;
228 		case IEEE80211_M_IBSS:
229 		case IEEE80211_M_AHDEMO:
230 		case IEEE80211_M_HOSTAP:
231 			if (dir != IEEE80211_FC1_DIR_NODS)
232 				bssid = wh->i_addr1;
233 			else if (type == IEEE80211_FC0_TYPE_CTL)
234 				bssid = wh->i_addr1;
235 			else {
236 				if (m->m_pkthdr.len < sizeof(struct ieee80211_frame)) {
237 					IEEE80211_DISCARD_MAC(ic,
238 					    IEEE80211_MSG_ANY, ni->ni_macaddr,
239 					    NULL, "too short (2): len %u",
240 					    m->m_pkthdr.len);
241 					ic->ic_stats.is_rx_tooshort++;
242 					goto out;
243 				}
244 				bssid = wh->i_addr3;
245 			}
246 			if (type != IEEE80211_FC0_TYPE_DATA)
247 				break;
248 			/*
249 			 * Data frame, validate the bssid.
250 			 */
251 			if (!IEEE80211_ADDR_EQ(bssid, ic->ic_bss->ni_bssid) &&
252 			    !IEEE80211_ADDR_EQ(bssid, ifp->if_broadcastaddr)) {
253 				/* not interested in */
254 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_INPUT,
255 				    bssid, NULL, "%s", "not to bss");
256 				ic->ic_stats.is_rx_wrongbss++;
257 				goto out;
258 			}
259 			/*
260 			 * For adhoc mode we cons up a node when it doesn't
261 			 * exist. This should probably done after an ACL check.
262 			 */
263 			if (ni == ic->ic_bss &&
264 			    ic->ic_opmode != IEEE80211_M_HOSTAP) {
265 				/*
266 				 * Fake up a node for this newly
267 				 * discovered member of the IBSS.
268 				 */
269 				ni = ieee80211_fakeup_adhoc_node(&ic->ic_sta,
270 						    wh->i_addr2);
271 				if (ni == NULL) {
272 					/* NB: stat kept for alloc failure */
273 					goto err;
274 				}
275 			}
276 			break;
277 		default:
278 			goto out;
279 		}
280 		ni->ni_rssi = rssi;
281 		ni->ni_rstamp = rstamp;
282 		if (HAS_SEQ(type)) {
283 			u_int8_t tid;
284 			if (IEEE80211_QOS_HAS_SEQ(wh)) {
285 				tid = ((struct ieee80211_qosframe *)wh)->
286 					i_qos[0] & IEEE80211_QOS_TID;
287 				if (TID_TO_WME_AC(tid) >= WME_AC_VI)
288 					ic->ic_wme.wme_hipri_traffic++;
289 				tid++;
290 			} else
291 				tid = 0;
292 			rxseq = le16toh(*(u_int16_t *)wh->i_seq);
293 			if ((wh->i_fc[1] & IEEE80211_FC1_RETRY) &&
294 			    SEQ_LEQ(rxseq, ni->ni_rxseqs[tid])) {
295 				/* duplicate, discard */
296 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_INPUT,
297 				    bssid, "duplicate",
298 				    "seqno <%u,%u> fragno <%u,%u> tid %u",
299 				    rxseq >> IEEE80211_SEQ_SEQ_SHIFT,
300 				    ni->ni_rxseqs[tid] >>
301 					IEEE80211_SEQ_SEQ_SHIFT,
302 				    rxseq & IEEE80211_SEQ_FRAG_MASK,
303 				    ni->ni_rxseqs[tid] &
304 					IEEE80211_SEQ_FRAG_MASK,
305 				    tid);
306 				ic->ic_stats.is_rx_dup++;
307 				IEEE80211_NODE_STAT(ni, rx_dup);
308 				goto out;
309 			}
310 			ni->ni_rxseqs[tid] = rxseq;
311 		}
312 	}
313 
314 	switch (type) {
315 	case IEEE80211_FC0_TYPE_DATA:
316 		hdrspace = ieee80211_hdrspace(ic, wh);
317 		if (m->m_len < hdrspace &&
318 		    (m = m_pullup(m, hdrspace)) == NULL) {
319 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_ANY,
320 			    ni->ni_macaddr, NULL,
321 			    "data too short: expecting %u", hdrspace);
322 			ic->ic_stats.is_rx_tooshort++;
323 			goto out;		/* XXX */
324 		}
325 		switch (ic->ic_opmode) {
326 		case IEEE80211_M_STA:
327 			if (dir != IEEE80211_FC1_DIR_FROMDS) {
328 				ic->ic_stats.is_rx_wrongdir++;
329 				goto out;
330 			}
331 			if (ic->ic_state != IEEE80211_S_SCAN &&
332 			    !IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_bssid)) {
333 				/* Source address is not our BSS. */
334 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_INPUT,
335 					"%s: discard frame from SA %s\n",
336 					__func__, ether_sprintf(wh->i_addr2));
337 				ic->ic_stats.is_rx_wrongbss++;
338 				goto out;
339 			}
340 			if ((ifp->if_flags & IFF_SIMPLEX) &&
341 			    IEEE80211_IS_MULTICAST(wh->i_addr1) &&
342 			    IEEE80211_ADDR_EQ(wh->i_addr3, ic->ic_myaddr)) {
343 				/*
344 				 * In IEEE802.11 network, multicast packet
345 				 * sent from me is broadcasted from AP.
346 				 * It should be silently discarded for
347 				 * SIMPLEX interface.
348 				 */
349 				IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
350 				    wh, NULL, "%s", "multicast echo");
351 				ic->ic_stats.is_rx_mcastecho++;
352 				goto out;
353 			}
354 			break;
355 		case IEEE80211_M_IBSS:
356 		case IEEE80211_M_AHDEMO:
357 			if (dir != IEEE80211_FC1_DIR_NODS) {
358 				ic->ic_stats.is_rx_wrongdir++;
359 				goto out;
360 			}
361 			/* XXX no power-save support */
362 			break;
363 		case IEEE80211_M_HOSTAP:
364 #ifndef IEEE80211_NO_HOSTAP
365 			if (dir != IEEE80211_FC1_DIR_TODS) {
366 				ic->ic_stats.is_rx_wrongdir++;
367 				goto out;
368 			}
369 			if (ic->ic_state != IEEE80211_S_SCAN &&
370 			    !IEEE80211_ADDR_EQ(wh->i_addr1, ic->ic_bss->ni_bssid) &&
371 			    !IEEE80211_ADDR_EQ(wh->i_addr1, ifp->if_broadcastaddr)) {
372 				/* BSS is not us or broadcast. */
373 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_INPUT,
374 					"%s: discard data frame to BSS %s\n",
375 					__func__, ether_sprintf(wh->i_addr1));
376 				ic->ic_stats.is_rx_wrongbss++;
377 				goto out;
378 			}
379 			/* check if source STA is associated */
380 			if (ni == ic->ic_bss) {
381 				IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
382 				    wh, "data", "%s", "unknown src");
383 				ieee80211_send_error(ic, ni, wh->i_addr2,
384 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
385 				    IEEE80211_REASON_NOT_AUTHED);
386 				ic->ic_stats.is_rx_notassoc++;
387 				goto err;
388 			}
389 			if (ni->ni_associd == 0) {
390 				IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
391 				    wh, "data", "%s", "unassoc src");
392 				IEEE80211_SEND_MGMT(ic, ni,
393 				    IEEE80211_FC0_SUBTYPE_DISASSOC,
394 				    IEEE80211_REASON_NOT_ASSOCED);
395 				ic->ic_stats.is_rx_notassoc++;
396 				goto err;
397 			}
398 
399 			/*
400 			 * Check for power save state change.
401 			 */
402 			if (((wh->i_fc[1] & IEEE80211_FC1_PWR_MGT) ^
403 			    (ni->ni_flags & IEEE80211_NODE_PWR_MGT)))
404 				ieee80211_node_pwrsave(ni,
405 					wh->i_fc[1] & IEEE80211_FC1_PWR_MGT);
406 #endif /* !IEEE80211_NO_HOSTAP */
407 			break;
408 		default:
409 			/* XXX here to keep compiler happy */
410 			goto out;
411 		}
412 
413 		/*
414 		 * Handle privacy requirements.  Note that we
415 		 * must not be preempted from here until after
416 		 * we (potentially) call ieee80211_crypto_demic;
417 		 * otherwise we may violate assumptions in the
418 		 * crypto cipher modules used to do delayed update
419 		 * of replay sequence numbers.
420 		 */
421 		if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
422 			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0) {
423 				/*
424 				 * Discard encrypted frames when privacy is off.
425 				 */
426 				IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
427 				    wh, "WEP", "%s", "PRIVACY off");
428 				ic->ic_stats.is_rx_noprivacy++;
429 				IEEE80211_NODE_STAT(ni, rx_noprivacy);
430 				goto out;
431 			}
432 			key = ieee80211_crypto_decap(ic, ni, m, hdrspace);
433 			if (key == NULL) {
434 				/* NB: stats+msgs handled in crypto_decap */
435 				IEEE80211_NODE_STAT(ni, rx_wepfail);
436 				goto out;
437 			}
438 			wh = mtod(m, struct ieee80211_frame *);
439 			wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
440 		} else {
441 			key = NULL;
442 		}
443 
444 		/*
445 		 * Next up, any fragmentation.
446 		 */
447 		if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
448 			m = ieee80211_defrag(ic, ni, m, hdrspace);
449 			if (m == NULL) {
450 				/* Fragment dropped or frame not complete yet */
451 				goto out;
452 			}
453 		}
454 		wh = NULL;		/* no longer valid, catch any uses */
455 
456 		/*
457 		 * Next strip any MSDU crypto bits.
458 		 */
459 		if (key != NULL && !ieee80211_crypto_demic(ic, key, m, 0)) {
460 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_INPUT,
461 			    ni->ni_macaddr, "data", "%s", "demic error");
462 			IEEE80211_NODE_STAT(ni, rx_demicfail);
463 			goto out;
464 		}
465 
466 #if NBPFILTER > 0
467 		/* copy to listener after decrypt */
468 		if (ic->ic_rawbpf)
469 			bpf_mtap(ic->ic_rawbpf, m);
470 #endif
471 
472 		/*
473 		 * Finally, strip the 802.11 header.
474 		 */
475 		m = ieee80211_decap(ic, m, hdrspace);
476 		if (m == NULL) {
477 			/* don't count Null data frames as errors */
478 			if (subtype == IEEE80211_FC0_SUBTYPE_NODATA)
479 				goto out;
480 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_INPUT,
481 			    ni->ni_macaddr, "data", "%s", "decap error");
482 			ic->ic_stats.is_rx_decap++;
483 			IEEE80211_NODE_STAT(ni, rx_decap);
484 			goto err;
485 		}
486 		eh = mtod(m, struct ether_header *);
487 		if (!ieee80211_node_is_authorized(ni)) {
488 			/*
489 			 * Deny any non-PAE frames received prior to
490 			 * authorization.  For open/shared-key
491 			 * authentication the port is mark authorized
492 			 * after authentication completes.  For 802.1x
493 			 * the port is not marked authorized by the
494 			 * authenticator until the handshake has completed.
495 			 */
496 			if (eh->ether_type != htons(ETHERTYPE_PAE)) {
497 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_INPUT,
498 				    eh->ether_shost, "data",
499 				    "unauthorized port: ether type 0x%x len %u",
500 				    eh->ether_type, m->m_pkthdr.len);
501 				ic->ic_stats.is_rx_unauth++;
502 				IEEE80211_NODE_STAT(ni, rx_unauth);
503 				goto err;
504 			}
505 		} else {
506 			/*
507 			 * When denying unencrypted frames, discard
508 			 * any non-PAE frames received without encryption.
509 			 */
510 			if ((ic->ic_flags & IEEE80211_F_DROPUNENC) &&
511 			    key == NULL &&
512 			    eh->ether_type != htons(ETHERTYPE_PAE)) {
513 				/*
514 				 * Drop unencrypted frames.
515 				 */
516 				ic->ic_stats.is_rx_unencrypted++;
517 				IEEE80211_NODE_STAT(ni, rx_unencrypted);
518 				goto out;
519 			}
520 		}
521 		ifp->if_ipackets++;
522 		IEEE80211_NODE_STAT(ni, rx_data);
523 		IEEE80211_NODE_STAT_ADD(ni, rx_bytes, m->m_pkthdr.len);
524 
525 #ifndef IEEE80211_NO_HOSTAP
526 		/* perform as a bridge within the AP */
527 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
528 		    (ic->ic_flags & IEEE80211_F_NOBRIDGE) == 0) {
529 			struct mbuf *m1 = NULL;
530 
531 			if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
532 				m1 = m_copypacket(m, M_DONTWAIT);
533 				if (m1 == NULL)
534 					ifp->if_oerrors++;
535 				else
536 					m1->m_flags |= M_MCAST;
537 			} else {
538 				/* XXX this dups work done in ieee80211_encap */
539 				/* check if destination is associated */
540 				struct ieee80211_node *ni1 =
541 				    ieee80211_find_node(&ic->ic_sta,
542 							eh->ether_dhost);
543 				if (ni1 != NULL) {
544 					/* XXX check if authorized */
545 					if (ni1->ni_associd != 0) {
546 						m1 = m;
547 						m = NULL;
548 					}
549 					/* XXX statistic? */
550 					ieee80211_free_node(ni1);
551 				}
552 			}
553 			if (m1 != NULL) {
554 				int len;
555 #ifdef ALTQ
556 				if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
557 					altq_etherclassify(&ifp->if_snd, m1,
558 					    &pktattr);
559 				}
560 #endif
561 				len = m1->m_pkthdr.len;
562 				IF_ENQUEUE(&ifp->if_snd, m1);
563 				if (m != NULL)
564 					ifp->if_omcasts++;
565 				ifp->if_obytes += len;
566 			}
567 		}
568 #endif /* !IEEE80211_NO_HOSTAP */
569 		if (m != NULL) {
570 #if NBPFILTER > 0
571 			/*
572 			 * XXX If we forward packet into transmitter of the AP,
573 			 * we don't need to duplicate for DLT_EN10MB.
574 			 */
575 			if (ifp->if_bpf)
576 				bpf_mtap(ifp->if_bpf, m);
577 #endif
578 			if (ni->ni_vlan != 0) {
579 				/* attach vlan tag */
580 				/* XXX goto err? */
581 				VLAN_INPUT_TAG(ifp, m, ni->ni_vlan, goto out);
582 			}
583 			(*ifp->if_input)(ifp, m);
584 		}
585 		return IEEE80211_FC0_TYPE_DATA;
586 
587 	case IEEE80211_FC0_TYPE_MGT:
588 		IEEE80211_NODE_STAT(ni, rx_mgmt);
589 		if (dir != IEEE80211_FC1_DIR_NODS) {
590 			ic->ic_stats.is_rx_wrongdir++;
591 			goto err;
592 		}
593 		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame)) {
594 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_ANY,
595 			    ni->ni_macaddr, "mgt", "too short: len %u",
596 			    m->m_pkthdr.len);
597 			ic->ic_stats.is_rx_tooshort++;
598 			goto out;
599 		}
600 #ifdef IEEE80211_DEBUG
601 		if ((ieee80211_msg_debug(ic) && doprint(ic, subtype)) ||
602 		    ieee80211_msg_dumppkts(ic)) {
603 			if_printf(ic->ic_ifp, "received %s from %s rssi %d\n",
604 			    ieee80211_mgt_subtype_name[subtype >>
605 				IEEE80211_FC0_SUBTYPE_SHIFT],
606 			    ether_sprintf(wh->i_addr2), rssi);
607 		}
608 #endif
609 		if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
610 			if (subtype != IEEE80211_FC0_SUBTYPE_AUTH) {
611 				/*
612 				 * Only shared key auth frames with a challenge
613 				 * should be encrypted, discard all others.
614 				 */
615 				IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
616 				    wh, ieee80211_mgt_subtype_name[subtype >>
617 					IEEE80211_FC0_SUBTYPE_SHIFT],
618 				    "%s", "WEP set but not permitted");
619 				ic->ic_stats.is_rx_mgtdiscard++; /* XXX */
620 				goto out;
621 			}
622 			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0) {
623 				/*
624 				 * Discard encrypted frames when privacy is off.
625 				 */
626 				IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
627 				    wh, "mgt", "%s", "WEP set but PRIVACY off");
628 				ic->ic_stats.is_rx_noprivacy++;
629 				goto out;
630 			}
631 			hdrspace = ieee80211_hdrspace(ic, wh);
632 			key = ieee80211_crypto_decap(ic, ni, m, hdrspace);
633 			if (key == NULL) {
634 				/* NB: stats+msgs handled in crypto_decap */
635 				goto out;
636 			}
637 			wh = mtod(m, struct ieee80211_frame *);
638 			wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
639 		}
640 #if NBPFILTER > 0
641 		if (ic->ic_rawbpf)
642 			bpf_mtap(ic->ic_rawbpf, m);
643 #endif
644 		(*ic->ic_recv_mgmt)(ic, m, ni, subtype, rssi, rstamp);
645 		m_freem(m);
646 		return type;
647 
648 	case IEEE80211_FC0_TYPE_CTL:
649 		IEEE80211_NODE_STAT(ni, rx_ctrl);
650 		ic->ic_stats.is_rx_ctl++;
651 #ifndef IEEE80211_NO_HOSTAP
652 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
653 			switch (subtype) {
654 			case IEEE80211_FC0_SUBTYPE_PS_POLL:
655 				ieee80211_recv_pspoll(ic, ni, m);
656 				break;
657 			}
658 		}
659 #endif /* !IEEE80211_NO_HOSTAP */
660 		goto out;
661 	default:
662 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
663 		    wh, NULL, "bad frame type 0x%x", type);
664 		/* should not come here */
665 		break;
666 	}
667 err:
668 	ifp->if_ierrors++;
669 out:
670 	if (m != NULL) {
671 #if NBPFILTER > 0
672 		if (ic->ic_rawbpf)
673 			bpf_mtap(ic->ic_rawbpf, m);
674 #endif
675 		m_freem(m);
676 	}
677 	return type;
678 #undef SEQ_LEQ
679 }
680 
681 /*
682  * This function reassemble fragments.
683  */
684 static struct mbuf *
685 ieee80211_defrag(struct ieee80211com *ic, struct ieee80211_node *ni,
686 	struct mbuf *m, int hdrspace)
687 {
688 	struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
689 	struct ieee80211_frame *lwh;
690 	u_int16_t rxseq;
691 	u_int8_t fragno;
692 	u_int8_t more_frag = wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG;
693 	struct mbuf *mfrag;
694 
695 	IASSERT(!IEEE80211_IS_MULTICAST(wh->i_addr1), ("multicast fragm?"));
696 
697 	rxseq = le16toh(*(u_int16_t *)wh->i_seq);
698 	fragno = rxseq & IEEE80211_SEQ_FRAG_MASK;
699 
700 	/* Quick way out, if there's nothing to defragment */
701 	if (!more_frag && fragno == 0 && ni->ni_rxfrag[0] == NULL)
702 		return m;
703 
704 	/*
705 	 * Remove frag to insure it doesn't get reaped by timer.
706 	 */
707 	if (ni->ni_table == NULL) {
708 		/*
709 		 * Should never happen.  If the node is orphaned (not in
710 		 * the table) then input packets should not reach here.
711 		 * Otherwise, a concurrent request that yanks the table
712 		 * should be blocked by other interlocking and/or by first
713 		 * shutting the driver down.  Regardless, be defensive
714 		 * here and just bail
715 		 */
716 		/* XXX need msg+stat */
717 		m_freem(m);
718 		return NULL;
719 	}
720 	IEEE80211_NODE_LOCK(ni->ni_table);
721 	mfrag = ni->ni_rxfrag[0];
722 	ni->ni_rxfrag[0] = NULL;
723 	IEEE80211_NODE_UNLOCK(ni->ni_table);
724 
725 	/*
726 	 * Validate new fragment is in order and
727 	 * related to the previous ones.
728 	 */
729 	if (mfrag != NULL) {
730 		u_int16_t last_rxseq;
731 
732 		lwh = mtod(mfrag, struct ieee80211_frame *);
733 		last_rxseq = le16toh(*(u_int16_t *)lwh->i_seq);
734 		/* NB: check seq # and frag together */
735 		if (rxseq != last_rxseq+1 ||
736 		    !IEEE80211_ADDR_EQ(wh->i_addr1, lwh->i_addr1) ||
737 		    !IEEE80211_ADDR_EQ(wh->i_addr2, lwh->i_addr2)) {
738 			/*
739 			 * Unrelated fragment or no space for it,
740 			 * clear current fragments.
741 			 */
742 			m_freem(mfrag);
743 			mfrag = NULL;
744 		}
745 	}
746 
747  	if (mfrag == NULL) {
748 		if (fragno != 0) {		/* !first fragment, discard */
749 			IEEE80211_NODE_STAT(ni, rx_defrag);
750 			m_freem(m);
751 			return NULL;
752 		}
753 		mfrag = m;
754 	} else {				/* concatenate */
755 		m_adj(m, hdrspace);		/* strip header */
756 		m_cat(mfrag, m);
757 		/* NB: m_cat doesn't update the packet header */
758 		mfrag->m_pkthdr.len += m->m_pkthdr.len;
759 		/* track last seqnum and fragno */
760 		lwh = mtod(mfrag, struct ieee80211_frame *);
761 		*(u_int16_t *) lwh->i_seq = *(u_int16_t *) wh->i_seq;
762 	}
763 	if (more_frag) {			/* more to come, save */
764 		ni->ni_rxfragstamp = ticks;
765 		ni->ni_rxfrag[0] = mfrag;
766 		mfrag = NULL;
767 	}
768 	return mfrag;
769 }
770 
771 static struct mbuf *
772 ieee80211_decap(struct ieee80211com *ic, struct mbuf *m, int hdrlen)
773 {
774 	struct ieee80211_qosframe_addr4 wh;	/* Max size address frames */
775 	struct ether_header *eh;
776 	struct llc *llc;
777 
778 	if (m->m_len < hdrlen + sizeof(*llc) &&
779 	    (m = m_pullup(m, hdrlen + sizeof(*llc))) == NULL) {
780 		/* XXX stat, msg */
781 		return NULL;
782 	}
783 	memcpy(&wh, mtod(m, caddr_t), hdrlen);
784 	llc = (struct llc *)(mtod(m, caddr_t) + hdrlen);
785 	if (llc->llc_dsap == LLC_SNAP_LSAP && llc->llc_ssap == LLC_SNAP_LSAP &&
786 	    llc->llc_control == LLC_UI && llc->llc_snap.org_code[0] == 0 &&
787 	    llc->llc_snap.org_code[1] == 0 && llc->llc_snap.org_code[2] == 0) {
788 		m_adj(m, hdrlen + sizeof(struct llc) - sizeof(*eh));
789 		llc = NULL;
790 	} else {
791 		m_adj(m, hdrlen - sizeof(*eh));
792 	}
793 	eh = mtod(m, struct ether_header *);
794 	switch (wh.i_fc[1] & IEEE80211_FC1_DIR_MASK) {
795 	case IEEE80211_FC1_DIR_NODS:
796 		IEEE80211_ADDR_COPY(eh->ether_dhost, wh.i_addr1);
797 		IEEE80211_ADDR_COPY(eh->ether_shost, wh.i_addr2);
798 		break;
799 	case IEEE80211_FC1_DIR_TODS:
800 		IEEE80211_ADDR_COPY(eh->ether_dhost, wh.i_addr3);
801 		IEEE80211_ADDR_COPY(eh->ether_shost, wh.i_addr2);
802 		break;
803 	case IEEE80211_FC1_DIR_FROMDS:
804 		IEEE80211_ADDR_COPY(eh->ether_dhost, wh.i_addr1);
805 		IEEE80211_ADDR_COPY(eh->ether_shost, wh.i_addr3);
806 		break;
807 	case IEEE80211_FC1_DIR_DSTODS:
808 		IEEE80211_ADDR_COPY(eh->ether_dhost, wh.i_addr3);
809 		IEEE80211_ADDR_COPY(eh->ether_shost, wh.i_addr4);
810 		break;
811 	}
812 #ifdef ALIGNED_POINTER
813 	if (!ALIGNED_POINTER(mtod(m, caddr_t) + sizeof(*eh), u_int32_t)) {
814 		struct mbuf *n, *n0, **np;
815 		caddr_t newdata;
816 		int off, pktlen;
817 
818 		n0 = NULL;
819 		np = &n0;
820 		off = 0;
821 		pktlen = m->m_pkthdr.len;
822 		while (pktlen > off) {
823 			if (n0 == NULL) {
824 				MGETHDR(n, M_DONTWAIT, MT_DATA);
825 				if (n == NULL) {
826 					m_freem(m);
827 					return NULL;
828 				}
829 				M_MOVE_PKTHDR(n, m);
830 				n->m_len = MHLEN;
831 			} else {
832 				MGET(n, M_DONTWAIT, MT_DATA);
833 				if (n == NULL) {
834 					m_freem(m);
835 					m_freem(n0);
836 					return NULL;
837 				}
838 				n->m_len = MLEN;
839 			}
840 			if (pktlen - off >= MINCLSIZE) {
841 				MCLGET(n, M_DONTWAIT);
842 				if (n->m_flags & M_EXT)
843 					n->m_len = n->m_ext.ext_size;
844 			}
845 			if (n0 == NULL) {
846 				newdata =
847 				    (caddr_t)ALIGN(n->m_data + sizeof(*eh)) -
848 				    sizeof(*eh);
849 				n->m_len -= newdata - n->m_data;
850 				n->m_data = newdata;
851 			}
852 			if (n->m_len > pktlen - off)
853 				n->m_len = pktlen - off;
854 			m_copydata(m, off, n->m_len, mtod(n, caddr_t));
855 			off += n->m_len;
856 			*np = n;
857 			np = &n->m_next;
858 		}
859 		m_freem(m);
860 		m = n0;
861 	}
862 #endif /* ALIGNED_POINTER */
863 	if (llc != NULL) {
864 		eh = mtod(m, struct ether_header *);
865 		eh->ether_type = htons(m->m_pkthdr.len - sizeof(*eh));
866 	}
867 	return m;
868 }
869 
870 /*
871  * Install received rate set information in the node's state block.
872  */
873 static int
874 ieee80211_setup_rates(struct ieee80211com *ic, struct ieee80211_node *ni,
875 	u_int8_t *rates, u_int8_t *xrates, int flags)
876 {
877 	struct ieee80211_rateset *rs = &ni->ni_rates;
878 
879 	memset(rs, 0, sizeof(*rs));
880 	rs->rs_nrates = rates[1];
881 	memcpy(rs->rs_rates, rates + 2, rs->rs_nrates);
882 	if (xrates != NULL) {
883 		u_int8_t nxrates;
884 		/*
885 		 * Tack on 11g extended supported rate element.
886 		 */
887 		nxrates = xrates[1];
888 		if (rs->rs_nrates + nxrates > IEEE80211_RATE_MAXSIZE) {
889 			nxrates = IEEE80211_RATE_MAXSIZE - rs->rs_nrates;
890 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_XRATE,
891 			     "[%s] extended rate set too large;"
892 			     " only using %u of %u rates\n",
893 			     ether_sprintf(ni->ni_macaddr), nxrates, xrates[1]);
894 			ic->ic_stats.is_rx_rstoobig++;
895 		}
896 		memcpy(rs->rs_rates + rs->rs_nrates, xrates+2, nxrates);
897 		rs->rs_nrates += nxrates;
898 	}
899 	return ieee80211_fix_rate(ic, ni, flags);
900 }
901 
902 static void
903 ieee80211_auth_open(struct ieee80211com *ic, struct ieee80211_frame *wh,
904     struct ieee80211_node *ni, int rssi, u_int32_t rstamp, u_int16_t seq,
905     u_int16_t status)
906 {
907 
908 	if (ni->ni_authmode == IEEE80211_AUTH_SHARED) {
909 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
910 		    ni->ni_macaddr, "open auth",
911 		    "bad sta auth mode %u", ni->ni_authmode);
912 		ic->ic_stats.is_rx_bad_auth++;	/* XXX */
913 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
914 			/* XXX hack to workaround calling convention */
915 			ieee80211_send_error(ic, ni, wh->i_addr2,
916 			    IEEE80211_FC0_SUBTYPE_AUTH,
917 			    (seq + 1) | (IEEE80211_STATUS_ALG<<16));
918 		}
919 		return;
920 	}
921 	switch (ic->ic_opmode) {
922 	case IEEE80211_M_IBSS:
923 	case IEEE80211_M_AHDEMO:
924 	case IEEE80211_M_MONITOR:
925 		/* should not come here */
926 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
927 		    ni->ni_macaddr, "open auth",
928 		    "bad operating mode %u", ic->ic_opmode);
929 		break;
930 
931 	case IEEE80211_M_HOSTAP:
932 #ifndef IEEE80211_NO_HOSTAP
933 		if (ic->ic_state != IEEE80211_S_RUN ||
934 		    seq != IEEE80211_AUTH_OPEN_REQUEST) {
935 			ic->ic_stats.is_rx_bad_auth++;
936 			return;
937 		}
938 		/* always accept open authentication requests */
939 		if (ni == ic->ic_bss) {
940 			ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);
941 			if (ni == NULL)
942 				return;
943 		} else if ((ni->ni_flags & IEEE80211_NODE_AREF) == 0)
944 			(void) ieee80211_ref_node(ni);
945 		/*
946 		 * Mark the node as referenced to reflect that it's
947 		 * reference count has been bumped to insure it remains
948 		 * after the transaction completes.
949 		 */
950 		ni->ni_flags |= IEEE80211_NODE_AREF;
951 
952 		IEEE80211_SEND_MGMT(ic, ni,
953 			IEEE80211_FC0_SUBTYPE_AUTH, seq + 1);
954 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
955 		    "[%s] station authenticated (open)\n",
956 		    ether_sprintf(ni->ni_macaddr));
957 		/*
958 		 * When 802.1x is not in use mark the port
959 		 * authorized at this point so traffic can flow.
960 		 */
961 		if (ni->ni_authmode != IEEE80211_AUTH_8021X)
962 			ieee80211_node_authorize(ic, ni);
963 #endif /* !IEEE80211_NO_HOSTAP */
964 		break;
965 
966 	case IEEE80211_M_STA:
967 		if (ic->ic_state != IEEE80211_S_AUTH ||
968 		    seq != IEEE80211_AUTH_OPEN_RESPONSE) {
969 			ic->ic_stats.is_rx_bad_auth++;
970 			return;
971 		}
972 		if (status != 0) {
973 			IEEE80211_DPRINTF(ic,
974 			    IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
975 			    "[%s] open auth failed (reason %d)\n",
976 			    ether_sprintf(ni->ni_macaddr), status);
977 			/* XXX can this happen? */
978 			if (ni != ic->ic_bss)
979 				ni->ni_fails++;
980 			ic->ic_stats.is_rx_auth_fail++;
981 			ieee80211_new_state(ic, IEEE80211_S_SCAN, 0);
982 		} else
983 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
984 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
985 		break;
986 	}
987 }
988 
989 /*
990  * Send a management frame error response to the specified
991  * station.  If ni is associated with the station then use
992  * it; otherwise allocate a temporary node suitable for
993  * transmitting the frame and then free the reference so
994  * it will go away as soon as the frame has been transmitted.
995  */
996 static void
997 ieee80211_send_error(struct ieee80211com *ic, struct ieee80211_node *ni,
998 	const u_int8_t *mac, int subtype, int arg)
999 {
1000 	int istmp;
1001 
1002 	if (ni == ic->ic_bss) {
1003 		ni = ieee80211_dup_bss(&ic->ic_sta, mac);
1004 		if (ni == NULL) {
1005 			/* XXX msg */
1006 			return;
1007 		}
1008 		istmp = 1;
1009 	} else
1010 		istmp = 0;
1011 	IEEE80211_SEND_MGMT(ic, ni, subtype, arg);
1012 	if (istmp)
1013 		ieee80211_free_node(ni);
1014 }
1015 
1016 static int
1017 alloc_challenge(struct ieee80211com *ic, struct ieee80211_node *ni)
1018 {
1019 	if (ni->ni_challenge == NULL)
1020 		MALLOC(ni->ni_challenge, u_int32_t*, IEEE80211_CHALLENGE_LEN,
1021 		    M_DEVBUF, M_NOWAIT);
1022 	if (ni->ni_challenge == NULL) {
1023 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1024 		    "[%s] shared key challenge alloc failed\n",
1025 		    ether_sprintf(ni->ni_macaddr));
1026 		/* XXX statistic */
1027 	}
1028 	return (ni->ni_challenge != NULL);
1029 }
1030 
1031 /* XXX TODO: add statistics */
1032 static void
1033 ieee80211_auth_shared(struct ieee80211com *ic, struct ieee80211_frame *wh,
1034     u_int8_t *frm, u_int8_t *efrm, struct ieee80211_node *ni, int rssi,
1035     u_int32_t rstamp, u_int16_t seq, u_int16_t status)
1036 {
1037 	u_int8_t *challenge;
1038 	int estatus;
1039 
1040 	/*
1041 	 * NB: this can happen as we allow pre-shared key
1042 	 * authentication to be enabled w/o wep being turned
1043 	 * on so that configuration of these can be done
1044 	 * in any order.  It may be better to enforce the
1045 	 * ordering in which case this check would just be
1046 	 * for sanity/consistency.
1047 	 */
1048 	if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0) {
1049 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1050 		    ni->ni_macaddr, "shared key auth",
1051 		    "%s", " PRIVACY is disabled");
1052 		estatus = IEEE80211_STATUS_ALG;
1053 		goto bad;
1054 	}
1055 	/*
1056 	 * Pre-shared key authentication is evil; accept
1057 	 * it only if explicitly configured (it is supported
1058 	 * mainly for compatibility with clients like OS X).
1059 	 */
1060 	if (ni->ni_authmode != IEEE80211_AUTH_AUTO &&
1061 	    ni->ni_authmode != IEEE80211_AUTH_SHARED) {
1062 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1063 		    ni->ni_macaddr, "shared key auth",
1064 		    "bad sta auth mode %u", ni->ni_authmode);
1065 		ic->ic_stats.is_rx_bad_auth++;	/* XXX maybe a unique error? */
1066 		estatus = IEEE80211_STATUS_ALG;
1067 		goto bad;
1068 	}
1069 
1070 	challenge = NULL;
1071 	if (frm + 1 < efrm) {
1072 		if ((frm[1] + 2) > (efrm - frm)) {
1073 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1074 			    ni->ni_macaddr, "shared key auth",
1075 			    "ie %d/%d too long",
1076 			    frm[0], (frm[1] + 2) - (efrm - frm));
1077 			ic->ic_stats.is_rx_bad_auth++;
1078 			estatus = IEEE80211_STATUS_CHALLENGE;
1079 			goto bad;
1080 		}
1081 		if (*frm == IEEE80211_ELEMID_CHALLENGE)
1082 			challenge = frm;
1083 		frm += frm[1] + 2;
1084 	}
1085 	switch (seq) {
1086 	case IEEE80211_AUTH_SHARED_CHALLENGE:
1087 	case IEEE80211_AUTH_SHARED_RESPONSE:
1088 		if (challenge == NULL) {
1089 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1090 			    ni->ni_macaddr, "shared key auth",
1091 			    "%s", "no challenge");
1092 			ic->ic_stats.is_rx_bad_auth++;
1093 			estatus = IEEE80211_STATUS_CHALLENGE;
1094 			goto bad;
1095 		}
1096 		if (challenge[1] != IEEE80211_CHALLENGE_LEN) {
1097 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1098 			    ni->ni_macaddr, "shared key auth",
1099 			    "bad challenge len %d", challenge[1]);
1100 			ic->ic_stats.is_rx_bad_auth++;
1101 			estatus = IEEE80211_STATUS_CHALLENGE;
1102 			goto bad;
1103 		}
1104 	default:
1105 		break;
1106 	}
1107 	switch (ic->ic_opmode) {
1108 	case IEEE80211_M_MONITOR:
1109 	case IEEE80211_M_AHDEMO:
1110 	case IEEE80211_M_IBSS:
1111 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1112 		    ni->ni_macaddr, "shared key auth",
1113 		    "bad operating mode %u", ic->ic_opmode);
1114 		return;
1115 	case IEEE80211_M_HOSTAP:
1116 #ifndef IEEE80211_NO_HOSTAP
1117 	{
1118 		int allocbs;
1119 		if (ic->ic_state != IEEE80211_S_RUN) {
1120 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1121 			    ni->ni_macaddr, "shared key auth",
1122 			    "bad state %u", ic->ic_state);
1123 			estatus = IEEE80211_STATUS_ALG;	/* XXX */
1124 			goto bad;
1125 		}
1126 		switch (seq) {
1127 		case IEEE80211_AUTH_SHARED_REQUEST:
1128 			if (ni == ic->ic_bss) {
1129 				ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);
1130 				if (ni == NULL) {
1131 					/* NB: no way to return an error */
1132 					return;
1133 				}
1134 				allocbs = 1;
1135 			} else {
1136 				if ((ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1137 					(void) ieee80211_ref_node(ni);
1138 				allocbs = 0;
1139 			}
1140 			/*
1141 			 * Mark the node as referenced to reflect that it's
1142 			 * reference count has been bumped to insure it remains
1143 			 * after the transaction completes.
1144 			 */
1145 			ni->ni_flags |= IEEE80211_NODE_AREF;
1146 			ni->ni_rssi = rssi;
1147 			ni->ni_rstamp = rstamp;
1148 			if (!alloc_challenge(ic, ni)) {
1149 				/* NB: don't return error so they rexmit */
1150 				return;
1151 			}
1152 			get_random_bytes(ni->ni_challenge,
1153 				IEEE80211_CHALLENGE_LEN);
1154 			IEEE80211_DPRINTF(ic,
1155 				IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1156 				"[%s] shared key %sauth request\n",
1157 				ether_sprintf(ni->ni_macaddr),
1158 				allocbs ? "" : "re");
1159 			break;
1160 		case IEEE80211_AUTH_SHARED_RESPONSE:
1161 			if (ni == ic->ic_bss) {
1162 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1163 				    ni->ni_macaddr, "shared key response",
1164 				    "%s", "unknown station");
1165 				/* NB: don't send a response */
1166 				return;
1167 			}
1168 			if (ni->ni_challenge == NULL) {
1169 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1170 				    ni->ni_macaddr, "shared key response",
1171 				    "%s", "no challenge recorded");
1172 				ic->ic_stats.is_rx_bad_auth++;
1173 				estatus = IEEE80211_STATUS_CHALLENGE;
1174 				goto bad;
1175 			}
1176 			if (memcmp(ni->ni_challenge, &challenge[2],
1177 			           challenge[1]) != 0) {
1178 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1179 				    ni->ni_macaddr, "shared key response",
1180 				    "%s", "challenge mismatch");
1181 				ic->ic_stats.is_rx_auth_fail++;
1182 				estatus = IEEE80211_STATUS_CHALLENGE;
1183 				goto bad;
1184 			}
1185 			IEEE80211_DPRINTF(ic,
1186 			    IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1187 			    "[%s] station authenticated (shared key)\n",
1188 			    ether_sprintf(ni->ni_macaddr));
1189 			ieee80211_node_authorize(ic, ni);
1190 			break;
1191 		default:
1192 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1193 			    ni->ni_macaddr, "shared key auth",
1194 			    "bad seq %d", seq);
1195 			ic->ic_stats.is_rx_bad_auth++;
1196 			estatus = IEEE80211_STATUS_SEQUENCE;
1197 			goto bad;
1198 		}
1199 		IEEE80211_SEND_MGMT(ic, ni,
1200 			IEEE80211_FC0_SUBTYPE_AUTH, seq + 1);
1201 	}
1202 #endif /* !IEEE80211_NO_HOSTAP */
1203 		break;
1204 
1205 	case IEEE80211_M_STA:
1206 		if (ic->ic_state != IEEE80211_S_AUTH)
1207 			return;
1208 		switch (seq) {
1209 		case IEEE80211_AUTH_SHARED_PASS:
1210 			if (ni->ni_challenge != NULL) {
1211 				FREE(ni->ni_challenge, M_DEVBUF);
1212 				ni->ni_challenge = NULL;
1213 			}
1214 			if (status != 0) {
1215 				IEEE80211_DPRINTF(ic,
1216 				    IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1217 				    "[%s] shared key auth failed (reason %d)\n",
1218 				    ether_sprintf(ieee80211_getbssid(ic, wh)),
1219 				    status);
1220 				/* XXX can this happen? */
1221 				if (ni != ic->ic_bss)
1222 					ni->ni_fails++;
1223 				ic->ic_stats.is_rx_auth_fail++;
1224 				return;
1225 			}
1226 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
1227 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
1228 			break;
1229 		case IEEE80211_AUTH_SHARED_CHALLENGE:
1230 			if (!alloc_challenge(ic, ni))
1231 				return;
1232 			/* XXX could optimize by passing recvd challenge */
1233 			memcpy(ni->ni_challenge, &challenge[2], challenge[1]);
1234 			IEEE80211_SEND_MGMT(ic, ni,
1235 				IEEE80211_FC0_SUBTYPE_AUTH, seq + 1);
1236 			break;
1237 		default:
1238 			IEEE80211_DISCARD(ic, IEEE80211_MSG_AUTH,
1239 			    wh, "shared key auth", "bad seq %d", seq);
1240 			ic->ic_stats.is_rx_bad_auth++;
1241 			return;
1242 		}
1243 		break;
1244 	}
1245 	return;
1246 bad:
1247 #ifndef IEEE80211_NO_HOSTAP
1248 	/*
1249 	 * Send an error response; but only when operating as an AP.
1250 	 */
1251 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1252 		/* XXX hack to workaround calling convention */
1253 		ieee80211_send_error(ic, ni, wh->i_addr2,
1254 		    IEEE80211_FC0_SUBTYPE_AUTH,
1255 		    (seq + 1) | (estatus<<16));
1256 	} else if (ic->ic_opmode == IEEE80211_M_STA) {
1257 		/*
1258 		 * Kick the state machine.  This short-circuits
1259 		 * using the mgt frame timeout to trigger the
1260 		 * state transition.
1261 		 */
1262 		if (ic->ic_state == IEEE80211_S_AUTH)
1263 			ieee80211_new_state(ic, IEEE80211_S_SCAN, 0);
1264 	}
1265 #else
1266 	;
1267 #endif /* !IEEE80211_NO_HOSTAP */
1268 }
1269 
1270 /* Verify the existence and length of __elem or get out. */
1271 #define IEEE80211_VERIFY_ELEMENT(__elem, __maxlen) do {			\
1272 	if ((__elem) == NULL) {						\
1273 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,		\
1274 		    wh, ieee80211_mgt_subtype_name[subtype >>		\
1275 			IEEE80211_FC0_SUBTYPE_SHIFT],			\
1276 		    "%s", "no " #__elem );				\
1277 		ic->ic_stats.is_rx_elem_missing++;			\
1278 		return;							\
1279 	}								\
1280 	if ((__elem)[1] > (__maxlen)) {					\
1281 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,		\
1282 		    wh, ieee80211_mgt_subtype_name[subtype >>		\
1283 			IEEE80211_FC0_SUBTYPE_SHIFT],			\
1284 		    "bad " #__elem " len %d", (__elem)[1]);		\
1285 		ic->ic_stats.is_rx_elem_toobig++;			\
1286 		return;							\
1287 	}								\
1288 } while (0)
1289 
1290 #define	IEEE80211_VERIFY_LENGTH(_len, _minlen) do {			\
1291 	if ((_len) < (_minlen)) {					\
1292 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,		\
1293 		    wh, ieee80211_mgt_subtype_name[subtype >>		\
1294 			IEEE80211_FC0_SUBTYPE_SHIFT],			\
1295 		    "%s", "ie too short");				\
1296 		ic->ic_stats.is_rx_elem_toosmall++;			\
1297 		return;							\
1298 	}								\
1299 } while (0)
1300 
1301 #ifdef IEEE80211_DEBUG
1302 static void
1303 ieee80211_ssid_mismatch(struct ieee80211com *ic, const char *tag,
1304 	u_int8_t mac[IEEE80211_ADDR_LEN], u_int8_t *ssid)
1305 {
1306 	printf("[%s] discard %s frame, ssid mismatch: ",
1307 		ether_sprintf(mac), tag);
1308 	ieee80211_print_essid(ssid + 2, ssid[1]);
1309 	printf("\n");
1310 }
1311 
1312 #define	IEEE80211_VERIFY_SSID(_ni, _ssid) do {				\
1313 	if ((_ssid)[1] != 0 &&						\
1314 	    ((_ssid)[1] != (_ni)->ni_esslen ||				\
1315 	    memcmp((_ssid) + 2, (_ni)->ni_essid, (_ssid)[1]) != 0)) {	\
1316 		if (ieee80211_msg_input(ic))				\
1317 			ieee80211_ssid_mismatch(ic, 			\
1318 			    ieee80211_mgt_subtype_name[subtype >>	\
1319 				IEEE80211_FC0_SUBTYPE_SHIFT],		\
1320 				wh->i_addr2, _ssid);			\
1321 		ic->ic_stats.is_rx_ssidmismatch++;			\
1322 		return;							\
1323 	}								\
1324 } while (0)
1325 #else /* !IEEE80211_DEBUG */
1326 #define	IEEE80211_VERIFY_SSID(_ni, _ssid) do {				\
1327 	if ((_ssid)[1] != 0 &&						\
1328 	    ((_ssid)[1] != (_ni)->ni_esslen ||				\
1329 	    memcmp((_ssid) + 2, (_ni)->ni_essid, (_ssid)[1]) != 0)) {	\
1330 		ic->ic_stats.is_rx_ssidmismatch++;			\
1331 		return;							\
1332 	}								\
1333 } while (0)
1334 #endif /* !IEEE80211_DEBUG */
1335 
1336 /* unalligned little endian access */
1337 #define LE_READ_2(p)					\
1338 	((u_int16_t)					\
1339 	 ((((const u_int8_t *)(p))[0]      ) |		\
1340 	  (((const u_int8_t *)(p))[1] <<  8)))
1341 #define LE_READ_4(p)					\
1342 	((u_int32_t)					\
1343 	 ((((const u_int8_t *)(p))[0]      ) |		\
1344 	  (((const u_int8_t *)(p))[1] <<  8) |		\
1345 	  (((const u_int8_t *)(p))[2] << 16) |		\
1346 	  (((const u_int8_t *)(p))[3] << 24)))
1347 
1348 static int __inline
1349 iswpaoui(const u_int8_t *frm)
1350 {
1351 	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
1352 }
1353 
1354 static int __inline
1355 iswmeoui(const u_int8_t *frm)
1356 {
1357 	return frm[1] > 3 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI);
1358 }
1359 
1360 static int __inline
1361 iswmeparam(const u_int8_t *frm)
1362 {
1363 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1364 		frm[6] == WME_PARAM_OUI_SUBTYPE;
1365 }
1366 
1367 static int __inline
1368 iswmeinfo(const u_int8_t *frm)
1369 {
1370 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1371 		frm[6] == WME_INFO_OUI_SUBTYPE;
1372 }
1373 
1374 static int __inline
1375 isatherosoui(const u_int8_t *frm)
1376 {
1377 	return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
1378 }
1379 
1380 /*
1381  * Convert a WPA cipher selector OUI to an internal
1382  * cipher algorithm.  Where appropriate we also
1383  * record any key length.
1384  */
1385 static int
1386 wpa_cipher(u_int8_t *sel, u_int8_t *keylen)
1387 {
1388 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
1389 	u_int32_t w = LE_READ_4(sel);
1390 
1391 	switch (w) {
1392 	case WPA_SEL(WPA_CSE_NULL):
1393 		return IEEE80211_CIPHER_NONE;
1394 	case WPA_SEL(WPA_CSE_WEP40):
1395 		if (keylen)
1396 			*keylen = 40 / NBBY;
1397 		return IEEE80211_CIPHER_WEP;
1398 	case WPA_SEL(WPA_CSE_WEP104):
1399 		if (keylen)
1400 			*keylen = 104 / NBBY;
1401 		return IEEE80211_CIPHER_WEP;
1402 	case WPA_SEL(WPA_CSE_TKIP):
1403 		return IEEE80211_CIPHER_TKIP;
1404 	case WPA_SEL(WPA_CSE_CCMP):
1405 		return IEEE80211_CIPHER_AES_CCM;
1406 	}
1407 	return 32;		/* NB: so 1<< is discarded */
1408 #undef WPA_SEL
1409 }
1410 
1411 /*
1412  * Convert a WPA key management/authentication algorithm
1413  * to an internal code.
1414  */
1415 static int
1416 wpa_keymgmt(u_int8_t *sel)
1417 {
1418 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
1419 	u_int32_t w = LE_READ_4(sel);
1420 
1421 	switch (w) {
1422 	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
1423 		return WPA_ASE_8021X_UNSPEC;
1424 	case WPA_SEL(WPA_ASE_8021X_PSK):
1425 		return WPA_ASE_8021X_PSK;
1426 	case WPA_SEL(WPA_ASE_NONE):
1427 		return WPA_ASE_NONE;
1428 	}
1429 	return 0;		/* NB: so is discarded */
1430 #undef WPA_SEL
1431 }
1432 
1433 /*
1434  * Parse a WPA information element to collect parameters
1435  * and validate the parameters against what has been
1436  * configured for the system.
1437  */
1438 static int
1439 ieee80211_parse_wpa(struct ieee80211com *ic, u_int8_t *frm,
1440 	struct ieee80211_rsnparms *rsn, const struct ieee80211_frame *wh)
1441 {
1442 	u_int8_t len = frm[1];
1443 	u_int32_t w;
1444 	int n;
1445 
1446 	/*
1447 	 * Check the length once for fixed parts: OUI, type,
1448 	 * version, mcast cipher, and 2 selector counts.
1449 	 * Other, variable-length data, must be checked separately.
1450 	 */
1451 	IASSERT(ic->ic_flags & IEEE80211_F_WPA1,
1452 		("not WPA, flags 0x%x", ic->ic_flags));
1453 	if (len < 14) {
1454 		IEEE80211_DISCARD_IE(ic,
1455 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1456 		    wh, "WPA", "too short, len %u", len);
1457 		return IEEE80211_REASON_IE_INVALID;
1458 	}
1459 	frm += 6, len -= 4;		/* NB: len is payload only */
1460 	/* NB: iswapoui already validated the OUI and type */
1461 	w = LE_READ_2(frm);
1462 	if (w != WPA_VERSION) {
1463 		IEEE80211_DISCARD_IE(ic,
1464 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1465 		    wh, "WPA", "bad version %u", w);
1466 		return IEEE80211_REASON_IE_INVALID;
1467 	}
1468 	frm += 2, len -= 2;
1469 
1470 	/* multicast/group cipher */
1471 	w = wpa_cipher(frm, &rsn->rsn_mcastkeylen);
1472 	if (w != rsn->rsn_mcastcipher) {
1473 		IEEE80211_DISCARD_IE(ic,
1474 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1475 		    wh, "WPA", "mcast cipher mismatch; got %u, expected %u",
1476 		    w, rsn->rsn_mcastcipher);
1477 		return IEEE80211_REASON_IE_INVALID;
1478 	}
1479 	frm += 4, len -= 4;
1480 
1481 	/* unicast ciphers */
1482 	n = LE_READ_2(frm);
1483 	frm += 2, len -= 2;
1484 	if (len < n*4+2) {
1485 		IEEE80211_DISCARD_IE(ic,
1486 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1487 		    wh, "WPA", "ucast cipher data too short; len %u, n %u",
1488 		    len, n);
1489 		return IEEE80211_REASON_IE_INVALID;
1490 	}
1491 	w = 0;
1492 	for (; n > 0; n--) {
1493 		w |= 1<<wpa_cipher(frm, &rsn->rsn_ucastkeylen);
1494 		frm += 4, len -= 4;
1495 	}
1496 	w &= rsn->rsn_ucastcipherset;
1497 	if (w == 0) {
1498 		IEEE80211_DISCARD_IE(ic,
1499 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1500 		    wh, "WPA", "%s", "ucast cipher set empty");
1501 		return IEEE80211_REASON_IE_INVALID;
1502 	}
1503 	if (w & (1<<IEEE80211_CIPHER_TKIP))
1504 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_TKIP;
1505 	else
1506 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_AES_CCM;
1507 
1508 	/* key management algorithms */
1509 	n = LE_READ_2(frm);
1510 	frm += 2, len -= 2;
1511 	if (len < n*4) {
1512 		IEEE80211_DISCARD_IE(ic,
1513 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1514 		    wh, "WPA", "key mgmt alg data too short; len %u, n %u",
1515 		    len, n);
1516 		return IEEE80211_REASON_IE_INVALID;
1517 	}
1518 	w = 0;
1519 	for (; n > 0; n--) {
1520 		w |= wpa_keymgmt(frm);
1521 		frm += 4, len -= 4;
1522 	}
1523 	w &= rsn->rsn_keymgmtset;
1524 	if (w == 0) {
1525 		IEEE80211_DISCARD_IE(ic,
1526 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1527 		    wh, "WPA", "%s", "no acceptable key mgmt alg");
1528 		return IEEE80211_REASON_IE_INVALID;
1529 	}
1530 	if (w & WPA_ASE_8021X_UNSPEC)
1531 		rsn->rsn_keymgmt = WPA_ASE_8021X_UNSPEC;
1532 	else
1533 		rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
1534 
1535 	if (len > 2)		/* optional capabilities */
1536 		rsn->rsn_caps = LE_READ_2(frm);
1537 
1538 	return 0;
1539 }
1540 
1541 /*
1542  * Convert an RSN cipher selector OUI to an internal
1543  * cipher algorithm.  Where appropriate we also
1544  * record any key length.
1545  */
1546 static int
1547 rsn_cipher(u_int8_t *sel, u_int8_t *keylen)
1548 {
1549 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1550 	u_int32_t w = LE_READ_4(sel);
1551 
1552 	switch (w) {
1553 	case RSN_SEL(RSN_CSE_NULL):
1554 		return IEEE80211_CIPHER_NONE;
1555 	case RSN_SEL(RSN_CSE_WEP40):
1556 		if (keylen)
1557 			*keylen = 40 / NBBY;
1558 		return IEEE80211_CIPHER_WEP;
1559 	case RSN_SEL(RSN_CSE_WEP104):
1560 		if (keylen)
1561 			*keylen = 104 / NBBY;
1562 		return IEEE80211_CIPHER_WEP;
1563 	case RSN_SEL(RSN_CSE_TKIP):
1564 		return IEEE80211_CIPHER_TKIP;
1565 	case RSN_SEL(RSN_CSE_CCMP):
1566 		return IEEE80211_CIPHER_AES_CCM;
1567 	case RSN_SEL(RSN_CSE_WRAP):
1568 		return IEEE80211_CIPHER_AES_OCB;
1569 	}
1570 	return 32;		/* NB: so 1<< is discarded */
1571 #undef WPA_SEL
1572 }
1573 
1574 /*
1575  * Convert an RSN key management/authentication algorithm
1576  * to an internal code.
1577  */
1578 static int
1579 rsn_keymgmt(u_int8_t *sel)
1580 {
1581 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1582 	u_int32_t w = LE_READ_4(sel);
1583 
1584 	switch (w) {
1585 	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
1586 		return RSN_ASE_8021X_UNSPEC;
1587 	case RSN_SEL(RSN_ASE_8021X_PSK):
1588 		return RSN_ASE_8021X_PSK;
1589 	case RSN_SEL(RSN_ASE_NONE):
1590 		return RSN_ASE_NONE;
1591 	}
1592 	return 0;		/* NB: so is discarded */
1593 #undef RSN_SEL
1594 }
1595 
1596 /*
1597  * Parse a WPA/RSN information element to collect parameters
1598  * and validate the parameters against what has been
1599  * configured for the system.
1600  */
1601 static int
1602 ieee80211_parse_rsn(struct ieee80211com *ic, u_int8_t *frm,
1603 	struct ieee80211_rsnparms *rsn, const struct ieee80211_frame *wh)
1604 {
1605 	u_int8_t len = frm[1];
1606 	u_int32_t w;
1607 	int n;
1608 
1609 	/*
1610 	 * Check the length once for fixed parts:
1611 	 * version, mcast cipher, and 2 selector counts.
1612 	 * Other, variable-length data, must be checked separately.
1613 	 */
1614 	IASSERT(ic->ic_flags & IEEE80211_F_WPA2,
1615 		("not RSN, flags 0x%x", ic->ic_flags));
1616 	if (len < 10) {
1617 		IEEE80211_DISCARD_IE(ic,
1618 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1619 		    wh, "RSN", "too short, len %u", len);
1620 		return IEEE80211_REASON_IE_INVALID;
1621 	}
1622 	frm += 2;
1623 	w = LE_READ_2(frm);
1624 	if (w != RSN_VERSION) {
1625 		IEEE80211_DISCARD_IE(ic,
1626 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1627 		    wh, "RSN", "bad version %u", w);
1628 		return IEEE80211_REASON_IE_INVALID;
1629 	}
1630 	frm += 2, len -= 2;
1631 
1632 	/* multicast/group cipher */
1633 	w = rsn_cipher(frm, &rsn->rsn_mcastkeylen);
1634 	if (w != rsn->rsn_mcastcipher) {
1635 		IEEE80211_DISCARD_IE(ic,
1636 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1637 		    wh, "RSN", "mcast cipher mismatch; got %u, expected %u",
1638 		    w, rsn->rsn_mcastcipher);
1639 		return IEEE80211_REASON_IE_INVALID;
1640 	}
1641 	frm += 4, len -= 4;
1642 
1643 	/* unicast ciphers */
1644 	n = LE_READ_2(frm);
1645 	frm += 2, len -= 2;
1646 	if (len < n*4+2) {
1647 		IEEE80211_DISCARD_IE(ic,
1648 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1649 		    wh, "RSN", "ucast cipher data too short; len %u, n %u",
1650 		    len, n);
1651 		return IEEE80211_REASON_IE_INVALID;
1652 	}
1653 	w = 0;
1654 	for (; n > 0; n--) {
1655 		w |= 1<<rsn_cipher(frm, &rsn->rsn_ucastkeylen);
1656 		frm += 4, len -= 4;
1657 	}
1658 	w &= rsn->rsn_ucastcipherset;
1659 	if (w == 0) {
1660 		IEEE80211_DISCARD_IE(ic,
1661 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1662 		    wh, "RSN", "%s", "ucast cipher set empty");
1663 		return IEEE80211_REASON_IE_INVALID;
1664 	}
1665 	if (w & (1<<IEEE80211_CIPHER_TKIP))
1666 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_TKIP;
1667 	else
1668 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_AES_CCM;
1669 
1670 	/* key management algorithms */
1671 	n = LE_READ_2(frm);
1672 	frm += 2, len -= 2;
1673 	if (len < n*4) {
1674 		IEEE80211_DISCARD_IE(ic,
1675 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1676 		    wh, "RSN", "key mgmt alg data too short; len %u, n %u",
1677 		    len, n);
1678 		return IEEE80211_REASON_IE_INVALID;
1679 	}
1680 	w = 0;
1681 	for (; n > 0; n--) {
1682 		w |= rsn_keymgmt(frm);
1683 		frm += 4, len -= 4;
1684 	}
1685 	w &= rsn->rsn_keymgmtset;
1686 	if (w == 0) {
1687 		IEEE80211_DISCARD_IE(ic,
1688 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1689 		    wh, "RSN", "%s", "no acceptable key mgmt alg");
1690 		return IEEE80211_REASON_IE_INVALID;
1691 	}
1692 	if (w & RSN_ASE_8021X_UNSPEC)
1693 		rsn->rsn_keymgmt = RSN_ASE_8021X_UNSPEC;
1694 	else
1695 		rsn->rsn_keymgmt = RSN_ASE_8021X_PSK;
1696 
1697 	/* optional RSN capabilities */
1698 	if (len > 2)
1699 		rsn->rsn_caps = LE_READ_2(frm);
1700 	/* XXXPMKID */
1701 
1702 	return 0;
1703 }
1704 
1705 static int
1706 ieee80211_parse_wmeparams(struct ieee80211com *ic, u_int8_t *frm,
1707 	const struct ieee80211_frame *wh)
1708 {
1709 #define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
1710 	struct ieee80211_wme_state *wme = &ic->ic_wme;
1711 	u_int len = frm[1], qosinfo;
1712 	int i;
1713 
1714 	if (len < sizeof(struct ieee80211_wme_param)-2) {
1715 		IEEE80211_DISCARD_IE(ic,
1716 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WME,
1717 		    wh, "WME", "too short, len %u", len);
1718 		return -1;
1719 	}
1720 	qosinfo = frm[__offsetof(struct ieee80211_wme_param, param_qosInfo)];
1721 	qosinfo &= WME_QOSINFO_COUNT;
1722 	/* XXX do proper check for wraparound */
1723 	if (qosinfo == wme->wme_wmeChanParams.cap_info)
1724 		return 0;
1725 	frm += __offsetof(struct ieee80211_wme_param, params_acParams);
1726 	for (i = 0; i < WME_NUM_AC; i++) {
1727 		struct wmeParams *wmep =
1728 			&wme->wme_wmeChanParams.cap_wmeParams[i];
1729 		/* NB: ACI not used */
1730 		wmep->wmep_acm = MS(frm[0], WME_PARAM_ACM);
1731 		wmep->wmep_aifsn = MS(frm[0], WME_PARAM_AIFSN);
1732 		wmep->wmep_logcwmin = MS(frm[1], WME_PARAM_LOGCWMIN);
1733 		wmep->wmep_logcwmax = MS(frm[1], WME_PARAM_LOGCWMAX);
1734 		wmep->wmep_txopLimit = LE_READ_2(frm+2);
1735 		frm += 4;
1736 	}
1737 	wme->wme_wmeChanParams.cap_info = qosinfo;
1738 	return 1;
1739 #undef MS
1740 }
1741 
1742 static void
1743 ieee80211_saveie(u_int8_t **iep, const u_int8_t *ie)
1744 {
1745 	u_int ielen = ie[1]+2;
1746 	/*
1747 	 * Record information element for later use.
1748 	 */
1749 	if (*iep == NULL || (*iep)[1] != ie[1]) {
1750 		if (*iep != NULL)
1751 			FREE(*iep, M_DEVBUF);
1752 		MALLOC(*iep, void*, ielen, M_DEVBUF, M_NOWAIT);
1753 	}
1754 	if (*iep != NULL)
1755 		memcpy(*iep, ie, ielen);
1756 	/* XXX note failure */
1757 }
1758 
1759 #ifdef IEEE80211_DEBUG
1760 static void
1761 dump_probe_beacon(u_int8_t subtype, int isnew,
1762 	const u_int8_t mac[IEEE80211_ADDR_LEN],
1763 	u_int8_t chan, u_int8_t bchan, u_int16_t capinfo, u_int16_t bintval,
1764 	u_int8_t erp, u_int8_t *ssid, u_int8_t *country)
1765 {
1766 	printf("[%s] %s%s on chan %u (bss chan %u) ",
1767 	    ether_sprintf(mac), isnew ? "new " : "",
1768 	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1769 	    chan, bchan);
1770 	ieee80211_print_essid(ssid + 2, ssid[1]);
1771 	printf("\n");
1772 
1773 	if (isnew) {
1774 		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1775 			ether_sprintf(mac), capinfo, bintval, erp);
1776 		if (country) {
1777 #ifdef __FreeBSD__
1778 			printf(" country info %*D", country[1], country+2, " ");
1779 #else
1780 			int i;
1781 			printf(" country info");
1782 			for (i = 0; i < country[1]; i++)
1783 				printf(" %02x", country[i+2]);
1784 #endif
1785 		}
1786 		printf("\n");
1787 	}
1788 }
1789 #endif /* IEEE80211_DEBUG */
1790 
1791 void
1792 ieee80211_recv_mgmt(struct ieee80211com *ic, struct mbuf *m0,
1793 	struct ieee80211_node *ni,
1794 	int subtype, int rssi, u_int32_t rstamp)
1795 {
1796 #define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1797 #define	ISREASSOC(_st)	((_st) == IEEE80211_FC0_SUBTYPE_REASSOC_RESP)
1798 	struct ieee80211_frame *wh;
1799 	u_int8_t *frm, *efrm;
1800 	u_int8_t *ssid, *rates, *xrates, *wpa, *wme;
1801 	int reassoc, resp, allocbs;
1802 	u_int8_t rate;
1803 
1804 	wh = mtod(m0, struct ieee80211_frame *);
1805 	frm = (u_int8_t *)&wh[1];
1806 	efrm = mtod(m0, u_int8_t *) + m0->m_len;
1807 	switch (subtype) {
1808 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1809 	case IEEE80211_FC0_SUBTYPE_BEACON: {
1810 		u_int8_t *tstamp, *country, *tim;
1811 		u_int8_t chan, bchan, fhindex, erp;
1812 		u_int16_t capinfo, bintval, timoff;
1813 		u_int16_t fhdwell;
1814 
1815 		/*
1816 		 * We process beacon/probe response frames:
1817 		 *    o when scanning, or
1818 		 *    o station mode when associated (to collect state
1819 		 *      updates such as 802.11g slot time), or
1820 		 *    o adhoc mode (to discover neighbors)
1821 		 * Frames otherwise received are discarded.
1822 		 */
1823 		if (!((ic->ic_flags & IEEE80211_F_SCAN) ||
1824 		      (ic->ic_opmode == IEEE80211_M_STA && ni->ni_associd) ||
1825 		       ic->ic_opmode == IEEE80211_M_IBSS)) {
1826 			ic->ic_stats.is_rx_mgtdiscard++;
1827 			return;
1828 		}
1829 		/*
1830 		 * beacon/probe response frame format
1831 		 *	[8] time stamp
1832 		 *	[2] beacon interval
1833 		 *	[2] capability information
1834 		 *	[tlv] ssid
1835 		 *	[tlv] supported rates
1836 		 *	[tlv] country information
1837 		 *	[tlv] parameter set (FH/DS)
1838 		 *	[tlv] erp information
1839 		 *	[tlv] extended supported rates
1840 		 *	[tlv] WME
1841 		 *	[tlv] WPA or RSN
1842 		 */
1843 		IEEE80211_VERIFY_LENGTH(efrm - frm, 12);
1844 		tstamp  = frm;				frm += 8;
1845 		bintval = le16toh(*(u_int16_t *)frm);	frm += 2;
1846 		capinfo = le16toh(*(u_int16_t *)frm);	frm += 2;
1847 		ssid = rates = xrates = country = wpa = wme = tim = NULL;
1848 		bchan = ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan);
1849 		chan = bchan;
1850 		fhdwell = 0;
1851 		fhindex = 0;
1852 		erp = 0;
1853 		timoff = 0;
1854 		while (frm < efrm) {
1855 			switch (*frm) {
1856 			case IEEE80211_ELEMID_SSID:
1857 				ssid = frm;
1858 				break;
1859 			case IEEE80211_ELEMID_RATES:
1860 				rates = frm;
1861 				break;
1862 			case IEEE80211_ELEMID_COUNTRY:
1863 				country = frm;
1864 				break;
1865 			case IEEE80211_ELEMID_FHPARMS:
1866 				if (ic->ic_phytype == IEEE80211_T_FH) {
1867 					fhdwell = LE_READ_2(&frm[2]);
1868 					chan = IEEE80211_FH_CHAN(frm[4], frm[5]);
1869 					fhindex = frm[6];
1870 				}
1871 				break;
1872 			case IEEE80211_ELEMID_DSPARMS:
1873 				/*
1874 				 * XXX hack this since depending on phytype
1875 				 * is problematic for multi-mode devices.
1876 				 */
1877 				if (ic->ic_phytype != IEEE80211_T_FH)
1878 					chan = frm[2];
1879 				break;
1880 			case IEEE80211_ELEMID_TIM:
1881 				/* XXX ATIM? */
1882 				tim = frm;
1883 				timoff = frm - mtod(m0, u_int8_t *);
1884 				break;
1885 			case IEEE80211_ELEMID_IBSSPARMS:
1886 				break;
1887 			case IEEE80211_ELEMID_XRATES:
1888 				xrates = frm;
1889 				break;
1890 			case IEEE80211_ELEMID_ERP:
1891 				if (frm[1] != 1) {
1892 					IEEE80211_DISCARD_IE(ic,
1893 					    IEEE80211_MSG_ELEMID, wh, "ERP",
1894 					    "bad len %u", frm[1]);
1895 					ic->ic_stats.is_rx_elem_toobig++;
1896 					break;
1897 				}
1898 				erp = frm[2];
1899 				break;
1900 			case IEEE80211_ELEMID_RSN:
1901 				wpa = frm;
1902 				break;
1903 			case IEEE80211_ELEMID_VENDOR:
1904 				if (iswpaoui(frm))
1905 					wpa = frm;
1906 				else if (iswmeparam(frm) || iswmeinfo(frm))
1907 					wme = frm;
1908 				/* XXX Atheros OUI support */
1909 				break;
1910 			default:
1911 				IEEE80211_DISCARD_IE(ic, IEEE80211_MSG_ELEMID,
1912 				    wh, "unhandled",
1913 				    "id %u, len %u", *frm, frm[1]);
1914 				ic->ic_stats.is_rx_elem_unknown++;
1915 				break;
1916 			}
1917 			frm += frm[1] + 2;
1918 		}
1919 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
1920 		IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN);
1921 		if (
1922 #if IEEE80211_CHAN_MAX < 255
1923 		    chan > IEEE80211_CHAN_MAX ||
1924 #endif
1925 		    isclr(ic->ic_chan_active, chan)) {
1926 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,
1927 			    wh, ieee80211_mgt_subtype_name[subtype >>
1928 				IEEE80211_FC0_SUBTYPE_SHIFT],
1929 			    "invalid channel %u", chan);
1930 			ic->ic_stats.is_rx_badchan++;
1931 			return;
1932 		}
1933 		if (chan != bchan && ic->ic_phytype != IEEE80211_T_FH) {
1934 			/*
1935 			 * Frame was received on a channel different from the
1936 			 * one indicated in the DS params element id;
1937 			 * silently discard it.
1938 			 *
1939 			 * NB: this can happen due to signal leakage.
1940 			 *     But we should take it for FH phy because
1941 			 *     the rssi value should be correct even for
1942 			 *     different hop pattern in FH.
1943 			 */
1944 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,
1945 			    wh, ieee80211_mgt_subtype_name[subtype >>
1946 				IEEE80211_FC0_SUBTYPE_SHIFT],
1947 			    "for off-channel %u", chan);
1948 			ic->ic_stats.is_rx_chanmismatch++;
1949 			return;
1950 		}
1951 
1952 		if (ni != ic->ic_bss) {
1953 			ni = ieee80211_refine_node_for_beacon(ic, ni,
1954 					&ic->ic_channels[chan], ssid);
1955 		}
1956 		/*
1957 		 * Count frame now that we know it's to be processed.
1958 		 */
1959 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
1960 			ic->ic_stats.is_rx_beacon++;		/* XXX remove */
1961 			IEEE80211_NODE_STAT(ni, rx_beacons);
1962 		} else
1963 			IEEE80211_NODE_STAT(ni, rx_proberesp);
1964 
1965 		/*
1966 		 * When operating in station mode, check for state updates.
1967 		 * Be careful to ignore beacons received while doing a
1968 		 * background scan.  We consider only 11g/WMM stuff right now.
1969 		 */
1970 		if (ic->ic_opmode == IEEE80211_M_STA &&
1971 		    ni->ni_associd != 0 &&
1972 		    ((ic->ic_flags & IEEE80211_F_SCAN) == 0 ||
1973 		     IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_bssid))) {
1974 			/* record tsf of last beacon */
1975 			memcpy(ni->ni_tstamp.data, tstamp,
1976 				sizeof(ni->ni_tstamp));
1977 			if (ni->ni_erp != erp) {
1978 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1979 				    "[%s] erp change: was 0x%x, now 0x%x\n",
1980 				    ether_sprintf(wh->i_addr2),
1981 				    ni->ni_erp, erp);
1982 				if (ic->ic_curmode == IEEE80211_MODE_11G &&
1983 				    (ni->ni_erp & IEEE80211_ERP_USE_PROTECTION))
1984 					ic->ic_flags |= IEEE80211_F_USEPROT;
1985 				else
1986 					ic->ic_flags &= ~IEEE80211_F_USEPROT;
1987 				ni->ni_erp = erp;
1988 				/* XXX statistic */
1989 			}
1990 			if ((ni->ni_capinfo ^ capinfo) & IEEE80211_CAPINFO_SHORT_SLOTTIME) {
1991 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1992 				    "[%s] capabilities change: before 0x%x,"
1993 				     " now 0x%x\n",
1994 				     ether_sprintf(wh->i_addr2),
1995 				     ni->ni_capinfo, capinfo);
1996 				/*
1997 				 * NB: we assume short preamble doesn't
1998 				 *     change dynamically
1999 				 */
2000 				ieee80211_set_shortslottime(ic,
2001 					ic->ic_curmode == IEEE80211_MODE_11A ||
2002 					(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME));
2003 				ni->ni_capinfo = capinfo;
2004 				/* XXX statistic */
2005 			}
2006 			if (wme != NULL &&
2007 			    (ni->ni_flags & IEEE80211_NODE_QOS) &&
2008 			    ieee80211_parse_wmeparams(ic, wme, wh) > 0)
2009 				ieee80211_wme_updateparams(ic);
2010 			if (tim != NULL) {
2011 				struct ieee80211_tim_ie *ie =
2012 				    (struct ieee80211_tim_ie *) tim;
2013 
2014 				ni->ni_dtim_count = ie->tim_count;
2015 				ni->ni_dtim_period = ie->tim_period;
2016 			}
2017 			/* NB: don't need the rest of this */
2018 			if ((ic->ic_flags & IEEE80211_F_SCAN) == 0)
2019 				return;
2020 		}
2021 
2022 		if (ni == ic->ic_bss &&
2023 		    !IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_bssid)) {
2024 #ifdef IEEE80211_DEBUG
2025 			if (ieee80211_msg_scan(ic))
2026 				dump_probe_beacon(subtype, 1,
2027 				    wh->i_addr2, chan, bchan, capinfo,
2028 				    bintval, erp, ssid, country);
2029 #endif
2030 			/*
2031 			 * Create a new entry.  If scanning the entry goes
2032 			 * in the scan cache.  Otherwise, be particular when
2033 			 * operating in adhoc mode--only take nodes marked
2034 			 * as ibss participants so we don't populate our
2035 			 * neighbor table with unintersting sta's.
2036 			 */
2037 			if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
2038 				if ((capinfo & IEEE80211_CAPINFO_IBSS) == 0)
2039 					return;
2040 				ni = ieee80211_fakeup_adhoc_node(&ic->ic_sta,
2041 						wh->i_addr2);
2042 			} else
2043 				ni = ieee80211_dup_bss(&ic->ic_scan, wh->i_addr2);
2044 			if (ni == NULL)
2045 				return;
2046 			ni->ni_esslen = ssid[1];
2047 			memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
2048 			memcpy(ni->ni_essid, ssid + 2, ssid[1]);
2049 		} else if (ssid[1] != 0 &&
2050 		    (ISPROBE(subtype) || ni->ni_esslen == 0)) {
2051 			/*
2052 			 * Update ESSID at probe response to adopt
2053 			 * hidden AP by Lucent/Cisco, which announces
2054 			 * null ESSID in beacon.
2055 			 */
2056 #ifdef IEEE80211_DEBUG
2057 			if (ieee80211_msg_scan(ic) ||
2058 			    ieee80211_msg_debug(ic))
2059 				dump_probe_beacon(subtype, 0,
2060 				    wh->i_addr2, chan, bchan, capinfo,
2061 				    bintval, erp, ssid, country);
2062 #endif
2063 			ni->ni_esslen = ssid[1];
2064 			memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
2065 			memcpy(ni->ni_essid, ssid + 2, ssid[1]);
2066 		}
2067 		ni->ni_scangen = ic->ic_scan.nt_scangen;
2068 		IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
2069 		ni->ni_rssi = rssi;
2070 		ni->ni_rstamp = rstamp;
2071 		memcpy(ni->ni_tstamp.data, tstamp, sizeof(ni->ni_tstamp));
2072 		ni->ni_intval = bintval;
2073 		ni->ni_capinfo = capinfo;
2074 		ni->ni_chan = &ic->ic_channels[chan];
2075 		ni->ni_fhdwell = fhdwell;
2076 		ni->ni_fhindex = fhindex;
2077 		ni->ni_erp = erp;
2078 		if (tim != NULL) {
2079 			struct ieee80211_tim_ie *ie =
2080 			    (struct ieee80211_tim_ie *) tim;
2081 
2082 			ni->ni_dtim_count = ie->tim_count;
2083 			ni->ni_dtim_period = ie->tim_period;
2084 		}
2085 		/*
2086 		 * Record the byte offset from the mac header to
2087 		 * the start of the TIM information element for
2088 		 * use by hardware and/or to speedup software
2089 		 * processing of beacon frames.
2090 		 */
2091 		ni->ni_timoff = timoff;
2092 		/*
2093 		 * Record optional information elements that might be
2094 		 * used by applications or drivers.
2095 		 */
2096 		if (wme != NULL)
2097 			ieee80211_saveie(&ni->ni_wme_ie, wme);
2098 		if (wpa != NULL)
2099 			ieee80211_saveie(&ni->ni_wpa_ie, wpa);
2100 		/* NB: must be after ni_chan is setup */
2101 		ieee80211_setup_rates(ic, ni, rates, xrates, IEEE80211_F_DOSORT);
2102 		break;
2103 	}
2104 
2105 	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
2106 		if (ic->ic_opmode == IEEE80211_M_STA ||
2107 		    ic->ic_state != IEEE80211_S_RUN) {
2108 			ic->ic_stats.is_rx_mgtdiscard++;
2109 			return;
2110 		}
2111 		if (IEEE80211_IS_MULTICAST(wh->i_addr2)) {
2112 			/* frame must be directed */
2113 			ic->ic_stats.is_rx_mgtdiscard++;	/* XXX stat */
2114 			return;
2115 		}
2116 
2117 		/*
2118 		 * prreq frame format
2119 		 *	[tlv] ssid
2120 		 *	[tlv] supported rates
2121 		 *	[tlv] extended supported rates
2122 		 */
2123 		ssid = rates = xrates = NULL;
2124 		while (frm < efrm) {
2125 			switch (*frm) {
2126 			case IEEE80211_ELEMID_SSID:
2127 				ssid = frm;
2128 				break;
2129 			case IEEE80211_ELEMID_RATES:
2130 				rates = frm;
2131 				break;
2132 			case IEEE80211_ELEMID_XRATES:
2133 				xrates = frm;
2134 				break;
2135 			}
2136 			frm += frm[1] + 2;
2137 		}
2138 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
2139 		IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN);
2140 		IEEE80211_VERIFY_SSID(ic->ic_bss, ssid);
2141 		if ((ic->ic_flags & IEEE80211_F_HIDESSID) && ssid[1] == 0) {
2142 			IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
2143 			    wh, ieee80211_mgt_subtype_name[subtype >>
2144 				IEEE80211_FC0_SUBTYPE_SHIFT],
2145 			    "%s", "no ssid with ssid suppression enabled");
2146 			ic->ic_stats.is_rx_ssidmismatch++; /*XXX*/
2147 			return;
2148 		}
2149 
2150 		if (ni == ic->ic_bss) {
2151 			if (ic->ic_opmode == IEEE80211_M_IBSS) {
2152 				/*
2153 				 * XXX Cannot tell if the sender is operating
2154 				 * in ibss mode.  But we need a new node to
2155 				 * send the response so blindly add them to the
2156 				 * neighbor table.
2157 				 */
2158 				ni = ieee80211_fakeup_adhoc_node(&ic->ic_sta,
2159 					wh->i_addr2);
2160 			} else
2161 				ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);
2162 			if (ni == NULL)
2163 				return;
2164 			allocbs = 1;
2165 		} else
2166 			allocbs = 0;
2167 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2168 		    "[%s] recv probe req\n", ether_sprintf(wh->i_addr2));
2169 		ni->ni_rssi = rssi;
2170 		ni->ni_rstamp = rstamp;
2171 		rate = ieee80211_setup_rates(ic, ni, rates, xrates,
2172 			  IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE
2173 			| IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2174 		if (rate & IEEE80211_RATE_BASIC) {
2175 			IEEE80211_DISCARD(ic, IEEE80211_MSG_XRATE,
2176 			    wh, ieee80211_mgt_subtype_name[subtype >>
2177 				IEEE80211_FC0_SUBTYPE_SHIFT],
2178 			    "%s", "recv'd rate set invalid");
2179 		} else {
2180 			IEEE80211_SEND_MGMT(ic, ni,
2181 				IEEE80211_FC0_SUBTYPE_PROBE_RESP, 0);
2182 		}
2183 		if (allocbs && ic->ic_opmode != IEEE80211_M_IBSS) {
2184 			/* reclaim immediately */
2185 			ieee80211_free_node(ni);
2186 		}
2187 		break;
2188 
2189 	case IEEE80211_FC0_SUBTYPE_AUTH: {
2190 		u_int16_t algo, seq, status;
2191 		/*
2192 		 * auth frame format
2193 		 *	[2] algorithm
2194 		 *	[2] sequence
2195 		 *	[2] status
2196 		 *	[tlv*] challenge
2197 		 */
2198 		IEEE80211_VERIFY_LENGTH(efrm - frm, 6);
2199 		algo   = le16toh(*(u_int16_t *)frm);
2200 		seq    = le16toh(*(u_int16_t *)(frm + 2));
2201 		status = le16toh(*(u_int16_t *)(frm + 4));
2202 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
2203 		    "[%s] recv auth frame with algorithm %d seq %d\n",
2204 		    ether_sprintf(wh->i_addr2), algo, seq);
2205 		/*
2206 		 * Consult the ACL policy module if setup.
2207 		 */
2208 		if (ic->ic_acl != NULL &&
2209 		    !ic->ic_acl->iac_check(ic, wh->i_addr2)) {
2210 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ACL,
2211 			    wh, "auth", "%s", "disallowed by ACL");
2212 			ic->ic_stats.is_rx_acl++;
2213 			return;
2214 		}
2215 		if (ic->ic_flags & IEEE80211_F_COUNTERM) {
2216 			IEEE80211_DISCARD(ic,
2217 			    IEEE80211_MSG_AUTH | IEEE80211_MSG_CRYPTO,
2218 			    wh, "auth", "%s", "TKIP countermeasures enabled");
2219 			ic->ic_stats.is_rx_auth_countermeasures++;
2220 #ifndef IEEE80211_NO_HOSTAP
2221 			if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2222 				IEEE80211_SEND_MGMT(ic, ni,
2223 					IEEE80211_FC0_SUBTYPE_AUTH,
2224 					IEEE80211_REASON_MIC_FAILURE);
2225 			}
2226 #endif /* !IEEE80211_NO_HOSTAP */
2227 			return;
2228 		}
2229 		if (algo == IEEE80211_AUTH_ALG_SHARED)
2230 			ieee80211_auth_shared(ic, wh, frm + 6, efrm, ni, rssi,
2231 			    rstamp, seq, status);
2232 		else if (algo == IEEE80211_AUTH_ALG_OPEN)
2233 			ieee80211_auth_open(ic, wh, ni, rssi, rstamp, seq,
2234 			    status);
2235 		else {
2236 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
2237 			    wh, "auth", "unsupported alg %d", algo);
2238 			ic->ic_stats.is_rx_auth_unsupported++;
2239 #ifndef IEEE80211_NO_HOSTAP
2240 			if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2241 				/* XXX not right */
2242 				IEEE80211_SEND_MGMT(ic, ni,
2243 					IEEE80211_FC0_SUBTYPE_AUTH,
2244 					(seq+1) | (IEEE80211_STATUS_ALG<<16));
2245 			}
2246 #endif /* !IEEE80211_NO_HOSTAP */
2247 			return;
2248 		}
2249 		break;
2250 	}
2251 
2252 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
2253 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ: {
2254 		u_int16_t capinfo, bintval;
2255 		struct ieee80211_rsnparms rsn;
2256 		u_int8_t reason;
2257 
2258 		if (ic->ic_opmode != IEEE80211_M_HOSTAP ||
2259 		    ic->ic_state != IEEE80211_S_RUN) {
2260 			ic->ic_stats.is_rx_mgtdiscard++;
2261 			return;
2262 		}
2263 
2264 		if (subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
2265 			reassoc = 1;
2266 			resp = IEEE80211_FC0_SUBTYPE_REASSOC_RESP;
2267 		} else {
2268 			reassoc = 0;
2269 			resp = IEEE80211_FC0_SUBTYPE_ASSOC_RESP;
2270 		}
2271 		/*
2272 		 * asreq frame format
2273 		 *	[2] capability information
2274 		 *	[2] listen interval
2275 		 *	[6*] current AP address (reassoc only)
2276 		 *	[tlv] ssid
2277 		 *	[tlv] supported rates
2278 		 *	[tlv] extended supported rates
2279 		 *	[tlv] WPA or RSN
2280 		 */
2281 		IEEE80211_VERIFY_LENGTH(efrm - frm, (reassoc ? 10 : 4));
2282 		if (!IEEE80211_ADDR_EQ(wh->i_addr3, ic->ic_bss->ni_bssid)) {
2283 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
2284 			    wh, ieee80211_mgt_subtype_name[subtype >>
2285 				IEEE80211_FC0_SUBTYPE_SHIFT],
2286 			    "%s", "wrong bssid");
2287 			ic->ic_stats.is_rx_assoc_bss++;
2288 			return;
2289 		}
2290 		capinfo = le16toh(*(u_int16_t *)frm);	frm += 2;
2291 		bintval = le16toh(*(u_int16_t *)frm);	frm += 2;
2292 		if (reassoc)
2293 			frm += 6;	/* ignore current AP info */
2294 		ssid = rates = xrates = wpa = wme = NULL;
2295 		while (frm < efrm) {
2296 			switch (*frm) {
2297 			case IEEE80211_ELEMID_SSID:
2298 				ssid = frm;
2299 				break;
2300 			case IEEE80211_ELEMID_RATES:
2301 				rates = frm;
2302 				break;
2303 			case IEEE80211_ELEMID_XRATES:
2304 				xrates = frm;
2305 				break;
2306 			/* XXX verify only one of RSN and WPA ie's? */
2307 			case IEEE80211_ELEMID_RSN:
2308 				wpa = frm;
2309 				break;
2310 			case IEEE80211_ELEMID_VENDOR:
2311 				if (iswpaoui(frm)) {
2312 					if (ic->ic_flags & IEEE80211_F_WPA1)
2313 						wpa = frm;
2314 				} else if (iswmeinfo(frm))
2315 					wme = frm;
2316 				/* XXX Atheros OUI support */
2317 				break;
2318 			}
2319 			frm += frm[1] + 2;
2320 		}
2321 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
2322 		IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN);
2323 		IEEE80211_VERIFY_SSID(ic->ic_bss, ssid);
2324 
2325 		if (ni == ic->ic_bss) {
2326 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2327 			    "[%s] deny %s request, sta not authenticated\n",
2328 			    ether_sprintf(wh->i_addr2),
2329 			    reassoc ? "reassoc" : "assoc");
2330 			ieee80211_send_error(ic, ni, wh->i_addr2,
2331 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2332 			    IEEE80211_REASON_ASSOC_NOT_AUTHED);
2333 			ic->ic_stats.is_rx_assoc_notauth++;
2334 			return;
2335 		}
2336 		/* assert right associstion security credentials */
2337 		if (wpa == NULL && (ic->ic_flags & IEEE80211_F_WPA)) {
2338 			IEEE80211_DPRINTF(ic,
2339 			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_WPA,
2340 			    "[%s] no WPA/RSN IE in association request\n",
2341 			    ether_sprintf(wh->i_addr2));
2342 			IEEE80211_SEND_MGMT(ic, ni,
2343 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2344 			    IEEE80211_REASON_RSN_REQUIRED);
2345 			ieee80211_node_leave(ic, ni);
2346 			/* XXX distinguish WPA/RSN? */
2347 			ic->ic_stats.is_rx_assoc_badwpaie++;
2348 			return;
2349 		}
2350 		if (wpa != NULL) {
2351 			/*
2352 			 * Parse WPA information element.  Note that
2353 			 * we initialize the param block from the node
2354 			 * state so that information in the IE overrides
2355 			 * our defaults.  The resulting parameters are
2356 			 * installed below after the association is assured.
2357 			 */
2358 			rsn = ni->ni_rsn;
2359 			if (wpa[0] != IEEE80211_ELEMID_RSN)
2360 				reason = ieee80211_parse_wpa(ic, wpa, &rsn, wh);
2361 			else
2362 				reason = ieee80211_parse_rsn(ic, wpa, &rsn, wh);
2363 			if (reason != 0) {
2364 				IEEE80211_SEND_MGMT(ic, ni,
2365 				    IEEE80211_FC0_SUBTYPE_DEAUTH, reason);
2366 				ieee80211_node_leave(ic, ni);
2367 				/* XXX distinguish WPA/RSN? */
2368 				ic->ic_stats.is_rx_assoc_badwpaie++;
2369 				return;
2370 			}
2371 			IEEE80211_DPRINTF(ic,
2372 			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_WPA,
2373 			    "[%s] %s ie: mc %u/%u uc %u/%u key %u caps 0x%x\n",
2374 			    ether_sprintf(wh->i_addr2),
2375 			    wpa[0] != IEEE80211_ELEMID_RSN ?  "WPA" : "RSN",
2376 			    rsn.rsn_mcastcipher, rsn.rsn_mcastkeylen,
2377 			    rsn.rsn_ucastcipher, rsn.rsn_ucastkeylen,
2378 			    rsn.rsn_keymgmt, rsn.rsn_caps);
2379 		}
2380 		/* discard challenge after association */
2381 		if (ni->ni_challenge != NULL) {
2382 			FREE(ni->ni_challenge, M_DEVBUF);
2383 			ni->ni_challenge = NULL;
2384 		}
2385 		/* NB: 802.11 spec says to ignore station's privacy bit */
2386 		if ((capinfo & IEEE80211_CAPINFO_ESS) == 0) {
2387 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2388 			    "[%s] deny %s request, capability mismatch 0x%x\n",
2389 			    ether_sprintf(wh->i_addr2),
2390 			    reassoc ? "reassoc" : "assoc", capinfo);
2391 			IEEE80211_SEND_MGMT(ic, ni, resp,
2392 				IEEE80211_STATUS_CAPINFO);
2393 			ieee80211_node_leave(ic, ni);
2394 			ic->ic_stats.is_rx_assoc_capmismatch++;
2395 			return;
2396 		}
2397 		rate = ieee80211_setup_rates(ic, ni, rates, xrates,
2398 				IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
2399 				IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2400 		/*
2401 		 * If constrained to 11g-only stations reject an
2402 		 * 11b-only station.  We cheat a bit here by looking
2403 		 * at the max negotiated xmit rate and assuming anyone
2404 		 * with a best rate <24Mb/s is an 11b station.
2405 		 */
2406 		if ((rate & IEEE80211_RATE_BASIC) ||
2407 		    ((ic->ic_flags & IEEE80211_F_PUREG) && rate < 48)) {
2408 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2409 			    "[%s] deny %s request, rate set mismatch\n",
2410 			    ether_sprintf(wh->i_addr2),
2411 			    reassoc ? "reassoc" : "assoc");
2412 			IEEE80211_SEND_MGMT(ic, ni, resp,
2413 				IEEE80211_STATUS_BASIC_RATE);
2414 			ieee80211_node_leave(ic, ni);
2415 			ic->ic_stats.is_rx_assoc_norate++;
2416 			return;
2417 		}
2418 		ni->ni_rssi = rssi;
2419 		ni->ni_rstamp = rstamp;
2420 		ni->ni_intval = bintval;
2421 		ni->ni_capinfo = capinfo;
2422 		ni->ni_chan = ic->ic_bss->ni_chan;
2423 		ni->ni_fhdwell = ic->ic_bss->ni_fhdwell;
2424 		ni->ni_fhindex = ic->ic_bss->ni_fhindex;
2425 		if (wpa != NULL) {
2426 			/*
2427 			 * Record WPA/RSN parameters for station, mark
2428 			 * node as using WPA and record information element
2429 			 * for applications that require it.
2430 			 */
2431 			ni->ni_rsn = rsn;
2432 			ieee80211_saveie(&ni->ni_wpa_ie, wpa);
2433 		} else if (ni->ni_wpa_ie != NULL) {
2434 			/*
2435 			 * Flush any state from a previous association.
2436 			 */
2437 			FREE(ni->ni_wpa_ie, M_DEVBUF);
2438 			ni->ni_wpa_ie = NULL;
2439 		}
2440 		if (wme != NULL) {
2441 			/*
2442 			 * Record WME parameters for station, mark node
2443 			 * as capable of QoS and record information
2444 			 * element for applications that require it.
2445 			 */
2446 			ieee80211_saveie(&ni->ni_wme_ie, wme);
2447 			ni->ni_flags |= IEEE80211_NODE_QOS;
2448 		} else if (ni->ni_wme_ie != NULL) {
2449 			/*
2450 			 * Flush any state from a previous association.
2451 			 */
2452 			FREE(ni->ni_wme_ie, M_DEVBUF);
2453 			ni->ni_wme_ie = NULL;
2454 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
2455 		}
2456 		ieee80211_node_join(ic, ni, resp);
2457 		break;
2458 	}
2459 
2460 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
2461 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP: {
2462 		u_int16_t capinfo, associd;
2463 		u_int16_t status;
2464 
2465 		if (ic->ic_opmode != IEEE80211_M_STA ||
2466 		    ic->ic_state != IEEE80211_S_ASSOC) {
2467 			ic->ic_stats.is_rx_mgtdiscard++;
2468 			return;
2469 		}
2470 
2471 		/*
2472 		 * asresp frame format
2473 		 *	[2] capability information
2474 		 *	[2] status
2475 		 *	[2] association ID
2476 		 *	[tlv] supported rates
2477 		 *	[tlv] extended supported rates
2478 		 *	[tlv] WME
2479 		 */
2480 		IEEE80211_VERIFY_LENGTH(efrm - frm, 6);
2481 		ni = ic->ic_bss;
2482 		capinfo = le16toh(*(u_int16_t *)frm);
2483 		frm += 2;
2484 		status = le16toh(*(u_int16_t *)frm);
2485 		frm += 2;
2486 		if (status != 0) {
2487 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2488 			    "[%s] %sassoc failed (reason %d)\n",
2489 			    ether_sprintf(wh->i_addr2),
2490 			    ISREASSOC(subtype) ?  "re" : "", status);
2491 			if (ni != ic->ic_bss)	/* XXX never true? */
2492 				ni->ni_fails++;
2493 			ic->ic_stats.is_rx_auth_fail++;	/* XXX */
2494 			return;
2495 		}
2496 		associd = le16toh(*(u_int16_t *)frm);
2497 		frm += 2;
2498 
2499 		rates = xrates = wpa = wme = NULL;
2500 		while (frm < efrm) {
2501 			switch (*frm) {
2502 			case IEEE80211_ELEMID_RATES:
2503 				rates = frm;
2504 				break;
2505 			case IEEE80211_ELEMID_XRATES:
2506 				xrates = frm;
2507 				break;
2508 			case IEEE80211_ELEMID_VENDOR:
2509 				if (iswmeoui(frm))
2510 					wme = frm;
2511 				/* XXX Atheros OUI support */
2512 				break;
2513 			}
2514 			frm += frm[1] + 2;
2515 		}
2516 
2517 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
2518 		rate = ieee80211_setup_rates(ic, ni, rates, xrates,
2519 				IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
2520 				IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2521 		if (rate & IEEE80211_RATE_BASIC) {
2522 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2523 			    "[%s] %sassoc failed (rate set mismatch)\n",
2524 			    ether_sprintf(wh->i_addr2),
2525 			    ISREASSOC(subtype) ?  "re" : "");
2526 			if (ni != ic->ic_bss)	/* XXX never true? */
2527 				ni->ni_fails++;
2528 			ic->ic_stats.is_rx_assoc_norate++;
2529 			ieee80211_new_state(ic, IEEE80211_S_SCAN, 0);
2530 			return;
2531 		}
2532 
2533 		ni->ni_capinfo = capinfo;
2534 		ni->ni_associd = associd;
2535 		if (wme != NULL &&
2536 		    ieee80211_parse_wmeparams(ic, wme, wh) >= 0) {
2537 			ni->ni_flags |= IEEE80211_NODE_QOS;
2538 			ieee80211_wme_updateparams(ic);
2539 		} else
2540 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
2541 		/*
2542 		 * Configure state now that we are associated.
2543 		 *
2544 		 * XXX may need different/additional driver callbacks?
2545 		 */
2546 		if (ic->ic_curmode == IEEE80211_MODE_11A ||
2547 		    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
2548 			ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2549 			ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2550 		} else {
2551 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2552 			ic->ic_flags |= IEEE80211_F_USEBARKER;
2553 		}
2554 		ieee80211_set_shortslottime(ic,
2555 			ic->ic_curmode == IEEE80211_MODE_11A ||
2556 			(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME));
2557 		/*
2558 		 * Honor ERP protection.
2559 		 *
2560 		 * NB: ni_erp should zero for non-11g operation.
2561 		 * XXX check ic_curmode anyway?
2562 		 */
2563 		if (ic->ic_curmode == IEEE80211_MODE_11G &&
2564 		    (ni->ni_erp & IEEE80211_ERP_USE_PROTECTION))
2565 			ic->ic_flags |= IEEE80211_F_USEPROT;
2566 		else
2567 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2568 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2569 		    "[%s] %sassoc success: %s preamble, %s slot time%s%s\n",
2570 		    ether_sprintf(wh->i_addr2),
2571 		    ISREASSOC(subtype) ? "re" : "",
2572 		    ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
2573 		    ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
2574 		    ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : "",
2575 		    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2576 		);
2577 		ieee80211_new_state(ic, IEEE80211_S_RUN, subtype);
2578 		break;
2579 	}
2580 
2581 	case IEEE80211_FC0_SUBTYPE_DEAUTH: {
2582 		u_int16_t reason;
2583 
2584 		if (ic->ic_state == IEEE80211_S_SCAN) {
2585 			ic->ic_stats.is_rx_mgtdiscard++;
2586 			return;
2587 		}
2588 		/*
2589 		 * deauth frame format
2590 		 *	[2] reason
2591 		 */
2592 		IEEE80211_VERIFY_LENGTH(efrm - frm, 2);
2593 		reason = le16toh(*(u_int16_t *)frm);
2594 		ic->ic_stats.is_rx_deauth++;
2595 		IEEE80211_NODE_STAT(ni, rx_deauth);
2596 
2597 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
2598 		    "[%s] recv deauthenticate (reason %d)\n",
2599 		    ether_sprintf(ni->ni_macaddr), reason);
2600 		switch (ic->ic_opmode) {
2601 		case IEEE80211_M_STA:
2602 			ieee80211_new_state(ic, IEEE80211_S_AUTH,
2603 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2604 			break;
2605 		case IEEE80211_M_HOSTAP:
2606 #ifndef IEEE80211_NO_HOSTAP
2607 			if (ni != ic->ic_bss)
2608 				ieee80211_node_leave(ic, ni);
2609 #endif /* !IEEE80211_NO_HOSTAP */
2610 			break;
2611 		default:
2612 			ic->ic_stats.is_rx_mgtdiscard++;
2613 			break;
2614 		}
2615 		break;
2616 	}
2617 
2618 	case IEEE80211_FC0_SUBTYPE_DISASSOC: {
2619 		u_int16_t reason;
2620 
2621 		if (ic->ic_state != IEEE80211_S_RUN &&
2622 		    ic->ic_state != IEEE80211_S_ASSOC &&
2623 		    ic->ic_state != IEEE80211_S_AUTH) {
2624 			ic->ic_stats.is_rx_mgtdiscard++;
2625 			return;
2626 		}
2627 		/*
2628 		 * disassoc frame format
2629 		 *	[2] reason
2630 		 */
2631 		IEEE80211_VERIFY_LENGTH(efrm - frm, 2);
2632 		reason = le16toh(*(u_int16_t *)frm);
2633 		ic->ic_stats.is_rx_disassoc++;
2634 		IEEE80211_NODE_STAT(ni, rx_disassoc);
2635 
2636 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2637 		    "[%s] recv disassociated (reason %d)\n",
2638 		    ether_sprintf(ni->ni_macaddr), reason);
2639 		switch (ic->ic_opmode) {
2640 		case IEEE80211_M_STA:
2641 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
2642 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2643 			break;
2644 		case IEEE80211_M_HOSTAP:
2645 #ifndef IEEE80211_NO_HOSTAP
2646 			if (ni != ic->ic_bss)
2647 				ieee80211_node_leave(ic, ni);
2648 #endif /* !IEEE80211_NO_HOSTAP */
2649 			break;
2650 		default:
2651 			ic->ic_stats.is_rx_mgtdiscard++;
2652 			break;
2653 		}
2654 		break;
2655 	}
2656 	default:
2657 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
2658 		     wh, "mgt", "subtype 0x%x not handled", subtype);
2659 		ic->ic_stats.is_rx_badsubtype++;
2660 		break;
2661 	}
2662 #undef ISREASSOC
2663 #undef ISPROBE
2664 }
2665 #undef IEEE80211_VERIFY_LENGTH
2666 #undef IEEE80211_VERIFY_ELEMENT
2667 
2668 #ifndef IEEE80211_NO_HOSTAP
2669 /*
2670  * Handle station power-save state change.
2671  */
2672 static void
2673 ieee80211_node_pwrsave(struct ieee80211_node *ni, int enable)
2674 {
2675 	struct ieee80211com *ic = ni->ni_ic;
2676 	struct mbuf *m;
2677 
2678 	if (enable) {
2679 		if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) == 0)
2680 			ic->ic_ps_sta++;
2681 		ni->ni_flags |= IEEE80211_NODE_PWR_MGT;
2682 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2683 		    "[%s] power save mode on, %u sta's in ps mode\n",
2684 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
2685 		return;
2686 	}
2687 
2688 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT)
2689 		ic->ic_ps_sta--;
2690 	ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
2691 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2692 	    "[%s] power save mode off, %u sta's in ps mode\n",
2693 	    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
2694 	/* XXX if no stations in ps mode, flush mc frames */
2695 
2696 	/*
2697 	 * Flush queued unicast frames.
2698 	 */
2699 	if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0) {
2700 		if (ic->ic_set_tim != NULL)
2701 			ic->ic_set_tim(ic, ni, 0);	/* just in case */
2702 		return;
2703 	}
2704 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2705 	    "[%s] flush ps queue, %u packets queued\n",
2706 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_SAVEQ_QLEN(ni));
2707 	for (;;) {
2708 		int qlen;
2709 
2710 		IEEE80211_NODE_SAVEQ_DEQUEUE(ni, m, qlen);
2711 		if (m == NULL)
2712 			break;
2713 		/*
2714 		 * If this is the last packet, turn off the TIM bit.
2715 		 * If there are more packets, set the more packets bit
2716 		 * in the mbuf so ieee80211_encap will mark the 802.11
2717 		 * head to indicate more data frames will follow.
2718 		 */
2719 		if (qlen != 0)
2720 			m->m_flags |= M_MORE_DATA;
2721 		/* XXX need different driver interface */
2722 		/* XXX bypasses q max */
2723 		IF_ENQUEUE(&ic->ic_ifp->if_snd, m);
2724 	}
2725 	if (ic->ic_set_tim != NULL)
2726 		ic->ic_set_tim(ic, ni, 0);
2727 }
2728 
2729 /*
2730  * Process a received ps-poll frame.
2731  */
2732 static void
2733 ieee80211_recv_pspoll(struct ieee80211com *ic,
2734 	struct ieee80211_node *ni, struct mbuf *m0)
2735 {
2736 	struct ieee80211_frame_min *wh;
2737 	struct mbuf *m;
2738 	u_int16_t aid;
2739 	int qlen;
2740 
2741 	wh = mtod(m0, struct ieee80211_frame_min *);
2742 	if (ni->ni_associd == 0) {
2743 		IEEE80211_DISCARD(ic, IEEE80211_MSG_POWER | IEEE80211_MSG_DEBUG,
2744 		    (struct ieee80211_frame *) wh, "ps-poll",
2745 		    "%s", "unassociated station");
2746 		ic->ic_stats.is_ps_unassoc++;
2747 		IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_DEAUTH,
2748 			IEEE80211_REASON_NOT_ASSOCED);
2749 		return;
2750 	}
2751 
2752 	aid = le16toh(*(u_int16_t *)wh->i_dur);
2753 	if (aid != ni->ni_associd) {
2754 		IEEE80211_DISCARD(ic, IEEE80211_MSG_POWER | IEEE80211_MSG_DEBUG,
2755 		    (struct ieee80211_frame *) wh, "ps-poll",
2756 		    "aid mismatch: sta aid 0x%x poll aid 0x%x",
2757 		    ni->ni_associd, aid);
2758 		ic->ic_stats.is_ps_badaid++;
2759 		IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_DEAUTH,
2760 			IEEE80211_REASON_NOT_ASSOCED);
2761 		return;
2762 	}
2763 
2764 	/* Okay, take the first queued packet and put it out... */
2765 	IEEE80211_NODE_SAVEQ_DEQUEUE(ni, m, qlen);
2766 	if (m == NULL) {
2767 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2768 		    "[%s] recv ps-poll, but queue empty\n",
2769 		    ether_sprintf(wh->i_addr2));
2770 		ieee80211_send_nulldata(ic, ni);
2771 		ic->ic_stats.is_ps_qempty++;	/* XXX node stat */
2772 		if (ic->ic_set_tim != NULL)
2773 			ic->ic_set_tim(ic, ni, 0);	/* just in case */
2774 		return;
2775 	}
2776 	/*
2777 	 * If there are more packets, set the more packets bit
2778 	 * in the packet dispatched to the station; otherwise
2779 	 * turn off the TIM bit.
2780 	 */
2781 	if (qlen != 0) {
2782 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2783 		    "[%s] recv ps-poll, send packet, %u still queued\n",
2784 		    ether_sprintf(ni->ni_macaddr), qlen);
2785 		m->m_flags |= M_MORE_DATA;
2786 	} else {
2787 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2788 		    "[%s] recv ps-poll, send packet, queue empty\n",
2789 		    ether_sprintf(ni->ni_macaddr));
2790 		if (ic->ic_set_tim != NULL)
2791 			ic->ic_set_tim(ic, ni, 0);
2792 	}
2793 	m->m_flags |= M_PWR_SAV;		/* bypass PS handling */
2794 	IF_ENQUEUE(&ic->ic_ifp->if_snd, m);
2795 }
2796 #endif /* !IEEE80211_NO_HOSTAP */
2797 
2798 #ifdef IEEE80211_DEBUG
2799 /*
2800  * Debugging support.
2801  */
2802 
2803 /*
2804  * Return the bssid of a frame.
2805  */
2806 static const u_int8_t *
2807 ieee80211_getbssid(struct ieee80211com *ic, const struct ieee80211_frame *wh)
2808 {
2809 	if (ic->ic_opmode == IEEE80211_M_STA)
2810 		return wh->i_addr2;
2811 	if ((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_NODS)
2812 		return wh->i_addr1;
2813 	if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
2814 		return wh->i_addr1;
2815 	return wh->i_addr3;
2816 }
2817 
2818 static void
2819 ieee80211_discard_frame(struct ieee80211com *ic,
2820 	const struct ieee80211_frame *wh,
2821 	const char *type, const char *fmt, ...)
2822 {
2823 	va_list ap;
2824 
2825 	printf("[%s] discard ", ether_sprintf(ieee80211_getbssid(ic, wh)));
2826 	if (type != NULL)
2827 		printf(" %s frame, ", type);
2828 	else
2829 		printf(" frame, ");
2830 	va_start(ap, fmt);
2831 	vprintf(fmt, ap);
2832 	va_end(ap);
2833 	printf("\n");
2834 }
2835 
2836 static void
2837 ieee80211_discard_ie(struct ieee80211com *ic,
2838 	const struct ieee80211_frame *wh,
2839 	const char *type, const char *fmt, ...)
2840 {
2841 	va_list ap;
2842 
2843 	printf("[%s] discard ", ether_sprintf(ieee80211_getbssid(ic, wh)));
2844 	if (type != NULL)
2845 		printf(" %s information element, ", type);
2846 	else
2847 		printf(" information element, ");
2848 	va_start(ap, fmt);
2849 	vprintf(fmt, ap);
2850 	va_end(ap);
2851 	printf("\n");
2852 }
2853 
2854 static void
2855 ieee80211_discard_mac(struct ieee80211com *ic,
2856 	const u_int8_t mac[IEEE80211_ADDR_LEN],
2857 	const char *type, const char *fmt, ...)
2858 {
2859 	va_list ap;
2860 
2861 	printf("[%s] discard ", ether_sprintf(mac));
2862 	if (type != NULL)
2863 		printf(" %s frame, ", type);
2864 	else
2865 		printf(" frame, ");
2866 	va_start(ap, fmt);
2867 	vprintf(fmt, ap);
2868 	va_end(ap);
2869 	printf("\n");
2870 }
2871 #endif /* IEEE80211_DEBUG */
2872