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