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