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