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