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