xref: /freebsd/sys/net80211/ieee80211_input.c (revision 91c878a6935c5c2e99866eb267e5bc3028bf6d2f)
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 			/* XXX hack to workaround calling convention */
877 			ieee80211_send_error(ic, ni, wh->i_addr2,
878 			    IEEE80211_FC0_SUBTYPE_AUTH,
879 			    (seq + 1) | (IEEE80211_STATUS_ALG<<16));
880 		}
881 		return;
882 	}
883 	switch (ic->ic_opmode) {
884 	case IEEE80211_M_IBSS:
885 	case IEEE80211_M_AHDEMO:
886 	case IEEE80211_M_MONITOR:
887 		/* should not come here */
888 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
889 		    ni->ni_macaddr, "open auth",
890 		    "bad operating mode %u", ic->ic_opmode);
891 		break;
892 
893 	case IEEE80211_M_HOSTAP:
894 		if (ic->ic_state != IEEE80211_S_RUN ||
895 		    seq != IEEE80211_AUTH_OPEN_REQUEST) {
896 			ic->ic_stats.is_rx_bad_auth++;
897 			return;
898 		}
899 		/* always accept open authentication requests */
900 		if (ni == ic->ic_bss) {
901 			ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);
902 			if (ni == NULL)
903 				return;
904 		} else if ((ni->ni_flags & IEEE80211_NODE_AREF) == 0)
905 			(void) ieee80211_ref_node(ni);
906 		/*
907 		 * Mark the node as referenced to reflect that it's
908 		 * reference count has been bumped to insure it remains
909 		 * after the transaction completes.
910 		 */
911 		ni->ni_flags |= IEEE80211_NODE_AREF;
912 
913 		IEEE80211_SEND_MGMT(ic, ni,
914 			IEEE80211_FC0_SUBTYPE_AUTH, seq + 1);
915 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
916 		    "[%s] station authenticated (open)\n",
917 		    ether_sprintf(ni->ni_macaddr));
918 		/*
919 		 * When 802.1x is not in use mark the port
920 		 * authorized at this point so traffic can flow.
921 		 */
922 		if (ni->ni_authmode != IEEE80211_AUTH_8021X)
923 			ieee80211_node_authorize(ni);
924 		break;
925 
926 	case IEEE80211_M_STA:
927 		if (ic->ic_state != IEEE80211_S_AUTH ||
928 		    seq != IEEE80211_AUTH_OPEN_RESPONSE) {
929 			ic->ic_stats.is_rx_bad_auth++;
930 			return;
931 		}
932 		if (status != 0) {
933 			IEEE80211_DPRINTF(ic,
934 			    IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
935 			    "[%s] open auth failed (reason %d)\n",
936 			    ether_sprintf(ni->ni_macaddr), status);
937 			/* XXX can this happen? */
938 			if (ni != ic->ic_bss)
939 				ni->ni_fails++;
940 			ic->ic_stats.is_rx_auth_fail++;
941 			ieee80211_new_state(ic, IEEE80211_S_SCAN, 0);
942 		} else
943 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
944 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
945 		break;
946 	}
947 }
948 
949 /*
950  * Send a management frame error response to the specified
951  * station.  If ni is associated with the station then use
952  * it; otherwise allocate a temporary node suitable for
953  * transmitting the frame and then free the reference so
954  * it will go away as soon as the frame has been transmitted.
955  */
956 static void
957 ieee80211_send_error(struct ieee80211com *ic, struct ieee80211_node *ni,
958 	const u_int8_t *mac, int subtype, int arg)
959 {
960 	int istmp;
961 
962 	if (ni == ic->ic_bss) {
963 		ni = ieee80211_tmp_node(ic, mac);
964 		if (ni == NULL) {
965 			/* XXX msg */
966 			return;
967 		}
968 		istmp = 1;
969 	} else
970 		istmp = 0;
971 	IEEE80211_SEND_MGMT(ic, ni, subtype, arg);
972 	if (istmp)
973 		ieee80211_free_node(ni);
974 }
975 
976 static int
977 alloc_challenge(struct ieee80211com *ic, struct ieee80211_node *ni)
978 {
979 	if (ni->ni_challenge == NULL)
980 		MALLOC(ni->ni_challenge, u_int32_t*, IEEE80211_CHALLENGE_LEN,
981 		    M_DEVBUF, M_NOWAIT);
982 	if (ni->ni_challenge == NULL) {
983 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
984 		    "[%s] shared key challenge alloc failed\n",
985 		    ether_sprintf(ni->ni_macaddr));
986 		/* XXX statistic */
987 	}
988 	return (ni->ni_challenge != NULL);
989 }
990 
991 /* XXX TODO: add statistics */
992 static void
993 ieee80211_auth_shared(struct ieee80211com *ic, struct ieee80211_frame *wh,
994     u_int8_t *frm, u_int8_t *efrm, struct ieee80211_node *ni, int rssi,
995     u_int32_t rstamp, u_int16_t seq, u_int16_t status)
996 {
997 	u_int8_t *challenge;
998 	int allocbs, estatus;
999 
1000 	/*
1001 	 * NB: this can happen as we allow pre-shared key
1002 	 * authentication to be enabled w/o wep being turned
1003 	 * on so that configuration of these can be done
1004 	 * in any order.  It may be better to enforce the
1005 	 * ordering in which case this check would just be
1006 	 * for sanity/consistency.
1007 	 */
1008 	if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0) {
1009 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1010 		    ni->ni_macaddr, "shared key auth",
1011 		    "%s", " PRIVACY is disabled");
1012 		estatus = IEEE80211_STATUS_ALG;
1013 		goto bad;
1014 	}
1015 	/*
1016 	 * Pre-shared key authentication is evil; accept
1017 	 * it only if explicitly configured (it is supported
1018 	 * mainly for compatibility with clients like OS X).
1019 	 */
1020 	if (ni->ni_authmode != IEEE80211_AUTH_AUTO &&
1021 	    ni->ni_authmode != IEEE80211_AUTH_SHARED) {
1022 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1023 		    ni->ni_macaddr, "shared key auth",
1024 		    "bad sta auth mode %u", ni->ni_authmode);
1025 		ic->ic_stats.is_rx_bad_auth++;	/* XXX maybe a unique error? */
1026 		estatus = IEEE80211_STATUS_ALG;
1027 		goto bad;
1028 	}
1029 
1030 	challenge = NULL;
1031 	if (frm + 1 < efrm) {
1032 		if ((frm[1] + 2) > (efrm - frm)) {
1033 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1034 			    ni->ni_macaddr, "shared key auth",
1035 			    "ie %d/%d too long",
1036 			    frm[0], (frm[1] + 2) - (efrm - frm));
1037 			ic->ic_stats.is_rx_bad_auth++;
1038 			estatus = IEEE80211_STATUS_CHALLENGE;
1039 			goto bad;
1040 		}
1041 		if (*frm == IEEE80211_ELEMID_CHALLENGE)
1042 			challenge = frm;
1043 		frm += frm[1] + 2;
1044 	}
1045 	switch (seq) {
1046 	case IEEE80211_AUTH_SHARED_CHALLENGE:
1047 	case IEEE80211_AUTH_SHARED_RESPONSE:
1048 		if (challenge == NULL) {
1049 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1050 			    ni->ni_macaddr, "shared key auth",
1051 			    "%s", "no challenge");
1052 			ic->ic_stats.is_rx_bad_auth++;
1053 			estatus = IEEE80211_STATUS_CHALLENGE;
1054 			goto bad;
1055 		}
1056 		if (challenge[1] != IEEE80211_CHALLENGE_LEN) {
1057 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1058 			    ni->ni_macaddr, "shared key auth",
1059 			    "bad challenge len %d", challenge[1]);
1060 			ic->ic_stats.is_rx_bad_auth++;
1061 			estatus = IEEE80211_STATUS_CHALLENGE;
1062 			goto bad;
1063 		}
1064 	default:
1065 		break;
1066 	}
1067 	switch (ic->ic_opmode) {
1068 	case IEEE80211_M_MONITOR:
1069 	case IEEE80211_M_AHDEMO:
1070 	case IEEE80211_M_IBSS:
1071 		IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1072 		    ni->ni_macaddr, "shared key auth",
1073 		    "bad operating mode %u", ic->ic_opmode);
1074 		return;
1075 	case IEEE80211_M_HOSTAP:
1076 		if (ic->ic_state != IEEE80211_S_RUN) {
1077 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1078 			    ni->ni_macaddr, "shared key auth",
1079 			    "bad state %u", ic->ic_state);
1080 			estatus = IEEE80211_STATUS_ALG;	/* XXX */
1081 			goto bad;
1082 		}
1083 		switch (seq) {
1084 		case IEEE80211_AUTH_SHARED_REQUEST:
1085 			if (ni == ic->ic_bss) {
1086 				ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);
1087 				if (ni == NULL) {
1088 					/* NB: no way to return an error */
1089 					return;
1090 				}
1091 				allocbs = 1;
1092 			} else {
1093 				if ((ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1094 					(void) ieee80211_ref_node(ni);
1095 				allocbs = 0;
1096 			}
1097 			/*
1098 			 * Mark the node as referenced to reflect that it's
1099 			 * reference count has been bumped to insure it remains
1100 			 * after the transaction completes.
1101 			 */
1102 			ni->ni_flags |= IEEE80211_NODE_AREF;
1103 			ni->ni_rssi = rssi;
1104 			ni->ni_rstamp = rstamp;
1105 			if (!alloc_challenge(ic, ni)) {
1106 				/* NB: don't return error so they rexmit */
1107 				return;
1108 			}
1109 			get_random_bytes(ni->ni_challenge,
1110 				IEEE80211_CHALLENGE_LEN);
1111 			IEEE80211_DPRINTF(ic,
1112 				IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1113 				"[%s] shared key %sauth request\n",
1114 				ether_sprintf(ni->ni_macaddr),
1115 				allocbs ? "" : "re");
1116 			break;
1117 		case IEEE80211_AUTH_SHARED_RESPONSE:
1118 			if (ni == ic->ic_bss) {
1119 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1120 				    ni->ni_macaddr, "shared key response",
1121 				    "%s", "unknown station");
1122 				/* NB: don't send a response */
1123 				return;
1124 			}
1125 			if (ni->ni_challenge == NULL) {
1126 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1127 				    ni->ni_macaddr, "shared key response",
1128 				    "%s", "no challenge recorded");
1129 				ic->ic_stats.is_rx_bad_auth++;
1130 				estatus = IEEE80211_STATUS_CHALLENGE;
1131 				goto bad;
1132 			}
1133 			if (memcmp(ni->ni_challenge, &challenge[2],
1134 			           challenge[1]) != 0) {
1135 				IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1136 				    ni->ni_macaddr, "shared key response",
1137 				    "%s", "challenge mismatch");
1138 				ic->ic_stats.is_rx_auth_fail++;
1139 				estatus = IEEE80211_STATUS_CHALLENGE;
1140 				goto bad;
1141 			}
1142 			IEEE80211_DPRINTF(ic,
1143 			    IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1144 			    "[%s] station authenticated (shared key)\n",
1145 			    ether_sprintf(ni->ni_macaddr));
1146 			ieee80211_node_authorize(ni);
1147 			break;
1148 		default:
1149 			IEEE80211_DISCARD_MAC(ic, IEEE80211_MSG_AUTH,
1150 			    ni->ni_macaddr, "shared key auth",
1151 			    "bad seq %d", seq);
1152 			ic->ic_stats.is_rx_bad_auth++;
1153 			estatus = IEEE80211_STATUS_SEQUENCE;
1154 			goto bad;
1155 		}
1156 		IEEE80211_SEND_MGMT(ic, ni,
1157 			IEEE80211_FC0_SUBTYPE_AUTH, seq + 1);
1158 		break;
1159 
1160 	case IEEE80211_M_STA:
1161 		if (ic->ic_state != IEEE80211_S_AUTH)
1162 			return;
1163 		switch (seq) {
1164 		case IEEE80211_AUTH_SHARED_PASS:
1165 			if (ni->ni_challenge != NULL) {
1166 				FREE(ni->ni_challenge, M_DEVBUF);
1167 				ni->ni_challenge = NULL;
1168 			}
1169 			if (status != 0) {
1170 				IEEE80211_DPRINTF(ic,
1171 				    IEEE80211_MSG_DEBUG | IEEE80211_MSG_AUTH,
1172 				    "[%s] shared key auth failed (reason %d)\n",
1173 				    ether_sprintf(ieee80211_getbssid(ic, wh)),
1174 				    status);
1175 				/* XXX can this happen? */
1176 				if (ni != ic->ic_bss)
1177 					ni->ni_fails++;
1178 				ic->ic_stats.is_rx_auth_fail++;
1179 				return;
1180 			}
1181 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
1182 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
1183 			break;
1184 		case IEEE80211_AUTH_SHARED_CHALLENGE:
1185 			if (!alloc_challenge(ic, ni))
1186 				return;
1187 			/* XXX could optimize by passing recvd challenge */
1188 			memcpy(ni->ni_challenge, &challenge[2], challenge[1]);
1189 			IEEE80211_SEND_MGMT(ic, ni,
1190 				IEEE80211_FC0_SUBTYPE_AUTH, seq + 1);
1191 			break;
1192 		default:
1193 			IEEE80211_DISCARD(ic, IEEE80211_MSG_AUTH,
1194 			    wh, "shared key auth", "bad seq %d", seq);
1195 			ic->ic_stats.is_rx_bad_auth++;
1196 			return;
1197 		}
1198 		break;
1199 	}
1200 	return;
1201 bad:
1202 	/*
1203 	 * Send an error response; but only when operating as an AP.
1204 	 */
1205 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1206 		/* XXX hack to workaround calling convention */
1207 		ieee80211_send_error(ic, ni, wh->i_addr2,
1208 		    IEEE80211_FC0_SUBTYPE_AUTH,
1209 		    (seq + 1) | (estatus<<16));
1210 	} else if (ic->ic_opmode == IEEE80211_M_STA) {
1211 		/*
1212 		 * Kick the state machine.  This short-circuits
1213 		 * using the mgt frame timeout to trigger the
1214 		 * state transition.
1215 		 */
1216 		if (ic->ic_state == IEEE80211_S_AUTH)
1217 			ieee80211_new_state(ic, IEEE80211_S_SCAN, 0);
1218 	}
1219 }
1220 
1221 /* Verify the existence and length of __elem or get out. */
1222 #define IEEE80211_VERIFY_ELEMENT(__elem, __maxlen) do {			\
1223 	if ((__elem) == NULL) {						\
1224 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,		\
1225 		    wh, ieee80211_mgt_subtype_name[subtype >>		\
1226 			IEEE80211_FC0_SUBTYPE_SHIFT],			\
1227 		    "%s", "no " #__elem );				\
1228 		ic->ic_stats.is_rx_elem_missing++;			\
1229 		return;							\
1230 	}								\
1231 	if ((__elem)[1] > (__maxlen)) {					\
1232 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,		\
1233 		    wh, ieee80211_mgt_subtype_name[subtype >>		\
1234 			IEEE80211_FC0_SUBTYPE_SHIFT],			\
1235 		    "bad " #__elem " len %d", (__elem)[1]);		\
1236 		ic->ic_stats.is_rx_elem_toobig++;			\
1237 		return;							\
1238 	}								\
1239 } while (0)
1240 
1241 #define	IEEE80211_VERIFY_LENGTH(_len, _minlen) do {			\
1242 	if ((_len) < (_minlen)) {					\
1243 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ELEMID,		\
1244 		    wh, ieee80211_mgt_subtype_name[subtype >>		\
1245 			IEEE80211_FC0_SUBTYPE_SHIFT],			\
1246 		    "%s", "ie too short");				\
1247 		ic->ic_stats.is_rx_elem_toosmall++;			\
1248 		return;							\
1249 	}								\
1250 } while (0)
1251 
1252 #ifdef IEEE80211_DEBUG
1253 static void
1254 ieee80211_ssid_mismatch(struct ieee80211com *ic, const char *tag,
1255 	u_int8_t mac[IEEE80211_ADDR_LEN], u_int8_t *ssid)
1256 {
1257 	printf("[%s] discard %s frame, ssid mismatch: ",
1258 		ether_sprintf(mac), tag);
1259 	ieee80211_print_essid(ssid + 2, ssid[1]);
1260 	printf("\n");
1261 }
1262 
1263 #define	IEEE80211_VERIFY_SSID(_ni, _ssid) do {				\
1264 	if ((_ssid)[1] != 0 &&						\
1265 	    ((_ssid)[1] != (_ni)->ni_esslen ||				\
1266 	    memcmp((_ssid) + 2, (_ni)->ni_essid, (_ssid)[1]) != 0)) {	\
1267 		if (ieee80211_msg_input(ic))				\
1268 			ieee80211_ssid_mismatch(ic, 			\
1269 			    ieee80211_mgt_subtype_name[subtype >>	\
1270 				IEEE80211_FC0_SUBTYPE_SHIFT],		\
1271 				wh->i_addr2, _ssid);			\
1272 		ic->ic_stats.is_rx_ssidmismatch++;			\
1273 		return;							\
1274 	}								\
1275 } while (0)
1276 #else /* !IEEE80211_DEBUG */
1277 #define	IEEE80211_VERIFY_SSID(_ni, _ssid) do {				\
1278 	if ((_ssid)[1] != 0 &&						\
1279 	    ((_ssid)[1] != (_ni)->ni_esslen ||				\
1280 	    memcmp((_ssid) + 2, (_ni)->ni_essid, (_ssid)[1]) != 0)) {	\
1281 		ic->ic_stats.is_rx_ssidmismatch++;			\
1282 		return;							\
1283 	}								\
1284 } while (0)
1285 #endif /* !IEEE80211_DEBUG */
1286 
1287 /* unalligned little endian access */
1288 #define LE_READ_2(p)					\
1289 	((u_int16_t)					\
1290 	 ((((const u_int8_t *)(p))[0]      ) |		\
1291 	  (((const u_int8_t *)(p))[1] <<  8)))
1292 #define LE_READ_4(p)					\
1293 	((u_int32_t)					\
1294 	 ((((const u_int8_t *)(p))[0]      ) |		\
1295 	  (((const u_int8_t *)(p))[1] <<  8) |		\
1296 	  (((const u_int8_t *)(p))[2] << 16) |		\
1297 	  (((const u_int8_t *)(p))[3] << 24)))
1298 
1299 static int __inline
1300 iswpaoui(const u_int8_t *frm)
1301 {
1302 	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
1303 }
1304 
1305 static int __inline
1306 iswmeoui(const u_int8_t *frm)
1307 {
1308 	return frm[1] > 3 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI);
1309 }
1310 
1311 static int __inline
1312 iswmeparam(const u_int8_t *frm)
1313 {
1314 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1315 		frm[6] == WME_PARAM_OUI_SUBTYPE;
1316 }
1317 
1318 static int __inline
1319 iswmeinfo(const u_int8_t *frm)
1320 {
1321 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1322 		frm[6] == WME_INFO_OUI_SUBTYPE;
1323 }
1324 
1325 static int __inline
1326 isatherosoui(const u_int8_t *frm)
1327 {
1328 	return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
1329 }
1330 
1331 /*
1332  * Convert a WPA cipher selector OUI to an internal
1333  * cipher algorithm.  Where appropriate we also
1334  * record any key length.
1335  */
1336 static int
1337 wpa_cipher(u_int8_t *sel, u_int8_t *keylen)
1338 {
1339 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
1340 	u_int32_t w = LE_READ_4(sel);
1341 
1342 	switch (w) {
1343 	case WPA_SEL(WPA_CSE_NULL):
1344 		return IEEE80211_CIPHER_NONE;
1345 	case WPA_SEL(WPA_CSE_WEP40):
1346 		if (keylen)
1347 			*keylen = 40 / NBBY;
1348 		return IEEE80211_CIPHER_WEP;
1349 	case WPA_SEL(WPA_CSE_WEP104):
1350 		if (keylen)
1351 			*keylen = 104 / NBBY;
1352 		return IEEE80211_CIPHER_WEP;
1353 	case WPA_SEL(WPA_CSE_TKIP):
1354 		return IEEE80211_CIPHER_TKIP;
1355 	case WPA_SEL(WPA_CSE_CCMP):
1356 		return IEEE80211_CIPHER_AES_CCM;
1357 	}
1358 	return 32;		/* NB: so 1<< is discarded */
1359 #undef WPA_SEL
1360 }
1361 
1362 /*
1363  * Convert a WPA key management/authentication algorithm
1364  * to an internal code.
1365  */
1366 static int
1367 wpa_keymgmt(u_int8_t *sel)
1368 {
1369 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
1370 	u_int32_t w = LE_READ_4(sel);
1371 
1372 	switch (w) {
1373 	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
1374 		return WPA_ASE_8021X_UNSPEC;
1375 	case WPA_SEL(WPA_ASE_8021X_PSK):
1376 		return WPA_ASE_8021X_PSK;
1377 	case WPA_SEL(WPA_ASE_NONE):
1378 		return WPA_ASE_NONE;
1379 	}
1380 	return 0;		/* NB: so is discarded */
1381 #undef WPA_SEL
1382 }
1383 
1384 /*
1385  * Parse a WPA information element to collect parameters
1386  * and validate the parameters against what has been
1387  * configured for the system.
1388  */
1389 static int
1390 ieee80211_parse_wpa(struct ieee80211com *ic, u_int8_t *frm,
1391 	struct ieee80211_rsnparms *rsn, const struct ieee80211_frame *wh)
1392 {
1393 	u_int8_t len = frm[1];
1394 	u_int32_t w;
1395 	int n;
1396 
1397 	/*
1398 	 * Check the length once for fixed parts: OUI, type,
1399 	 * version, mcast cipher, and 2 selector counts.
1400 	 * Other, variable-length data, must be checked separately.
1401 	 */
1402 	if ((ic->ic_flags & IEEE80211_F_WPA1) == 0) {
1403 		IEEE80211_DISCARD_IE(ic,
1404 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1405 		    wh, "WPA", "not WPA, flags 0x%x", ic->ic_flags);
1406 		return IEEE80211_REASON_IE_INVALID;
1407 	}
1408 	if (len < 14) {
1409 		IEEE80211_DISCARD_IE(ic,
1410 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1411 		    wh, "WPA", "too short, len %u", len);
1412 		return IEEE80211_REASON_IE_INVALID;
1413 	}
1414 	frm += 6, len -= 4;		/* NB: len is payload only */
1415 	/* NB: iswapoui already validated the OUI and type */
1416 	w = LE_READ_2(frm);
1417 	if (w != WPA_VERSION) {
1418 		IEEE80211_DISCARD_IE(ic,
1419 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1420 		    wh, "WPA", "bad version %u", w);
1421 		return IEEE80211_REASON_IE_INVALID;
1422 	}
1423 	frm += 2, len -= 2;
1424 
1425 	/* multicast/group cipher */
1426 	w = wpa_cipher(frm, &rsn->rsn_mcastkeylen);
1427 	if (w != rsn->rsn_mcastcipher) {
1428 		IEEE80211_DISCARD_IE(ic,
1429 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1430 		    wh, "WPA", "mcast cipher mismatch; got %u, expected %u",
1431 		    w, rsn->rsn_mcastcipher);
1432 		return IEEE80211_REASON_IE_INVALID;
1433 	}
1434 	frm += 4, len -= 4;
1435 
1436 	/* unicast ciphers */
1437 	n = LE_READ_2(frm);
1438 	frm += 2, len -= 2;
1439 	if (len < n*4+2) {
1440 		IEEE80211_DISCARD_IE(ic,
1441 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1442 		    wh, "WPA", "ucast cipher data too short; len %u, n %u",
1443 		    len, n);
1444 		return IEEE80211_REASON_IE_INVALID;
1445 	}
1446 	w = 0;
1447 	for (; n > 0; n--) {
1448 		w |= 1<<wpa_cipher(frm, &rsn->rsn_ucastkeylen);
1449 		frm += 4, len -= 4;
1450 	}
1451 	w &= rsn->rsn_ucastcipherset;
1452 	if (w == 0) {
1453 		IEEE80211_DISCARD_IE(ic,
1454 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1455 		    wh, "WPA", "%s", "ucast cipher set empty");
1456 		return IEEE80211_REASON_IE_INVALID;
1457 	}
1458 	if (w & (1<<IEEE80211_CIPHER_TKIP))
1459 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_TKIP;
1460 	else
1461 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_AES_CCM;
1462 
1463 	/* key management algorithms */
1464 	n = LE_READ_2(frm);
1465 	frm += 2, len -= 2;
1466 	if (len < n*4) {
1467 		IEEE80211_DISCARD_IE(ic,
1468 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1469 		    wh, "WPA", "key mgmt alg data too short; len %u, n %u",
1470 		    len, n);
1471 		return IEEE80211_REASON_IE_INVALID;
1472 	}
1473 	w = 0;
1474 	for (; n > 0; n--) {
1475 		w |= wpa_keymgmt(frm);
1476 		frm += 4, len -= 4;
1477 	}
1478 	w &= rsn->rsn_keymgmtset;
1479 	if (w == 0) {
1480 		IEEE80211_DISCARD_IE(ic,
1481 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1482 		    wh, "WPA", "%s", "no acceptable key mgmt alg");
1483 		return IEEE80211_REASON_IE_INVALID;
1484 	}
1485 	if (w & WPA_ASE_8021X_UNSPEC)
1486 		rsn->rsn_keymgmt = WPA_ASE_8021X_UNSPEC;
1487 	else
1488 		rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
1489 
1490 	if (len > 2)		/* optional capabilities */
1491 		rsn->rsn_caps = LE_READ_2(frm);
1492 
1493 	return 0;
1494 }
1495 
1496 /*
1497  * Convert an RSN cipher selector OUI to an internal
1498  * cipher algorithm.  Where appropriate we also
1499  * record any key length.
1500  */
1501 static int
1502 rsn_cipher(u_int8_t *sel, u_int8_t *keylen)
1503 {
1504 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1505 	u_int32_t w = LE_READ_4(sel);
1506 
1507 	switch (w) {
1508 	case RSN_SEL(RSN_CSE_NULL):
1509 		return IEEE80211_CIPHER_NONE;
1510 	case RSN_SEL(RSN_CSE_WEP40):
1511 		if (keylen)
1512 			*keylen = 40 / NBBY;
1513 		return IEEE80211_CIPHER_WEP;
1514 	case RSN_SEL(RSN_CSE_WEP104):
1515 		if (keylen)
1516 			*keylen = 104 / NBBY;
1517 		return IEEE80211_CIPHER_WEP;
1518 	case RSN_SEL(RSN_CSE_TKIP):
1519 		return IEEE80211_CIPHER_TKIP;
1520 	case RSN_SEL(RSN_CSE_CCMP):
1521 		return IEEE80211_CIPHER_AES_CCM;
1522 	case RSN_SEL(RSN_CSE_WRAP):
1523 		return IEEE80211_CIPHER_AES_OCB;
1524 	}
1525 	return 32;		/* NB: so 1<< is discarded */
1526 #undef WPA_SEL
1527 }
1528 
1529 /*
1530  * Convert an RSN key management/authentication algorithm
1531  * to an internal code.
1532  */
1533 static int
1534 rsn_keymgmt(u_int8_t *sel)
1535 {
1536 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1537 	u_int32_t w = LE_READ_4(sel);
1538 
1539 	switch (w) {
1540 	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
1541 		return RSN_ASE_8021X_UNSPEC;
1542 	case RSN_SEL(RSN_ASE_8021X_PSK):
1543 		return RSN_ASE_8021X_PSK;
1544 	case RSN_SEL(RSN_ASE_NONE):
1545 		return RSN_ASE_NONE;
1546 	}
1547 	return 0;		/* NB: so is discarded */
1548 #undef RSN_SEL
1549 }
1550 
1551 /*
1552  * Parse a WPA/RSN information element to collect parameters
1553  * and validate the parameters against what has been
1554  * configured for the system.
1555  */
1556 static int
1557 ieee80211_parse_rsn(struct ieee80211com *ic, u_int8_t *frm,
1558 	struct ieee80211_rsnparms *rsn, const struct ieee80211_frame *wh)
1559 {
1560 	u_int8_t len = frm[1];
1561 	u_int32_t w;
1562 	int n;
1563 
1564 	/*
1565 	 * Check the length once for fixed parts:
1566 	 * version, mcast cipher, and 2 selector counts.
1567 	 * Other, variable-length data, must be checked separately.
1568 	 */
1569 	if ((ic->ic_flags & IEEE80211_F_WPA2) == 0) {
1570 		IEEE80211_DISCARD_IE(ic,
1571 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1572 		    wh, "WPA", "not RSN, flags 0x%x", ic->ic_flags);
1573 		return IEEE80211_REASON_IE_INVALID;
1574 	}
1575 	if (len < 10) {
1576 		IEEE80211_DISCARD_IE(ic,
1577 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1578 		    wh, "RSN", "too short, len %u", len);
1579 		return IEEE80211_REASON_IE_INVALID;
1580 	}
1581 	frm += 2;
1582 	w = LE_READ_2(frm);
1583 	if (w != RSN_VERSION) {
1584 		IEEE80211_DISCARD_IE(ic,
1585 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1586 		    wh, "RSN", "bad version %u", w);
1587 		return IEEE80211_REASON_IE_INVALID;
1588 	}
1589 	frm += 2, len -= 2;
1590 
1591 	/* multicast/group cipher */
1592 	w = rsn_cipher(frm, &rsn->rsn_mcastkeylen);
1593 	if (w != rsn->rsn_mcastcipher) {
1594 		IEEE80211_DISCARD_IE(ic,
1595 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1596 		    wh, "RSN", "mcast cipher mismatch; got %u, expected %u",
1597 		    w, rsn->rsn_mcastcipher);
1598 		return IEEE80211_REASON_IE_INVALID;
1599 	}
1600 	frm += 4, len -= 4;
1601 
1602 	/* unicast ciphers */
1603 	n = LE_READ_2(frm);
1604 	frm += 2, len -= 2;
1605 	if (len < n*4+2) {
1606 		IEEE80211_DISCARD_IE(ic,
1607 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1608 		    wh, "RSN", "ucast cipher data too short; len %u, n %u",
1609 		    len, n);
1610 		return IEEE80211_REASON_IE_INVALID;
1611 	}
1612 	w = 0;
1613 	for (; n > 0; n--) {
1614 		w |= 1<<rsn_cipher(frm, &rsn->rsn_ucastkeylen);
1615 		frm += 4, len -= 4;
1616 	}
1617 	w &= rsn->rsn_ucastcipherset;
1618 	if (w == 0) {
1619 		IEEE80211_DISCARD_IE(ic,
1620 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1621 		    wh, "RSN", "%s", "ucast cipher set empty");
1622 		return IEEE80211_REASON_IE_INVALID;
1623 	}
1624 	if (w & (1<<IEEE80211_CIPHER_TKIP))
1625 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_TKIP;
1626 	else
1627 		rsn->rsn_ucastcipher = IEEE80211_CIPHER_AES_CCM;
1628 
1629 	/* key management algorithms */
1630 	n = LE_READ_2(frm);
1631 	frm += 2, len -= 2;
1632 	if (len < n*4) {
1633 		IEEE80211_DISCARD_IE(ic,
1634 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1635 		    wh, "RSN", "key mgmt alg data too short; len %u, n %u",
1636 		    len, n);
1637 		return IEEE80211_REASON_IE_INVALID;
1638 	}
1639 	w = 0;
1640 	for (; n > 0; n--) {
1641 		w |= rsn_keymgmt(frm);
1642 		frm += 4, len -= 4;
1643 	}
1644 	w &= rsn->rsn_keymgmtset;
1645 	if (w == 0) {
1646 		IEEE80211_DISCARD_IE(ic,
1647 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WPA,
1648 		    wh, "RSN", "%s", "no acceptable key mgmt alg");
1649 		return IEEE80211_REASON_IE_INVALID;
1650 	}
1651 	if (w & RSN_ASE_8021X_UNSPEC)
1652 		rsn->rsn_keymgmt = RSN_ASE_8021X_UNSPEC;
1653 	else
1654 		rsn->rsn_keymgmt = RSN_ASE_8021X_PSK;
1655 
1656 	/* optional RSN capabilities */
1657 	if (len > 2)
1658 		rsn->rsn_caps = LE_READ_2(frm);
1659 	/* XXXPMKID */
1660 
1661 	return 0;
1662 }
1663 
1664 static int
1665 ieee80211_parse_wmeparams(struct ieee80211com *ic, u_int8_t *frm,
1666 	const struct ieee80211_frame *wh)
1667 {
1668 #define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
1669 	struct ieee80211_wme_state *wme = &ic->ic_wme;
1670 	u_int len = frm[1], qosinfo;
1671 	int i;
1672 
1673 	if (len < sizeof(struct ieee80211_wme_param)-2) {
1674 		IEEE80211_DISCARD_IE(ic,
1675 		    IEEE80211_MSG_ELEMID | IEEE80211_MSG_WME,
1676 		    wh, "WME", "too short, len %u", len);
1677 		return -1;
1678 	}
1679 	qosinfo = frm[__offsetof(struct ieee80211_wme_param, param_qosInfo)];
1680 	qosinfo &= WME_QOSINFO_COUNT;
1681 	/* XXX do proper check for wraparound */
1682 	if (qosinfo == wme->wme_wmeChanParams.cap_info)
1683 		return 0;
1684 	frm += __offsetof(struct ieee80211_wme_param, params_acParams);
1685 	for (i = 0; i < WME_NUM_AC; i++) {
1686 		struct wmeParams *wmep =
1687 			&wme->wme_wmeChanParams.cap_wmeParams[i];
1688 		/* NB: ACI not used */
1689 		wmep->wmep_acm = MS(frm[0], WME_PARAM_ACM);
1690 		wmep->wmep_aifsn = MS(frm[0], WME_PARAM_AIFSN);
1691 		wmep->wmep_logcwmin = MS(frm[1], WME_PARAM_LOGCWMIN);
1692 		wmep->wmep_logcwmax = MS(frm[1], WME_PARAM_LOGCWMAX);
1693 		wmep->wmep_txopLimit = LE_READ_2(frm+2);
1694 		frm += 4;
1695 	}
1696 	wme->wme_wmeChanParams.cap_info = qosinfo;
1697 	return 1;
1698 #undef MS
1699 }
1700 
1701 void
1702 ieee80211_saveie(u_int8_t **iep, const u_int8_t *ie)
1703 {
1704 	u_int ielen = ie[1]+2;
1705 	/*
1706 	 * Record information element for later use.
1707 	 */
1708 	if (*iep == NULL || (*iep)[1] != ie[1]) {
1709 		if (*iep != NULL)
1710 			FREE(*iep, M_DEVBUF);
1711 		MALLOC(*iep, void*, ielen, M_DEVBUF, M_NOWAIT);
1712 	}
1713 	if (*iep != NULL)
1714 		memcpy(*iep, ie, ielen);
1715 	/* XXX note failure */
1716 }
1717 
1718 /* XXX find a better place for definition */
1719 struct l2_update_frame {
1720 	struct ether_header eh;
1721 	u_int8_t dsap;
1722 	u_int8_t ssap;
1723 	u_int8_t control;
1724 	u_int8_t xid[3];
1725 }  __packed;
1726 
1727 /*
1728  * Deliver a TGf L2UF frame on behalf of a station.
1729  * This primes any bridge when the station is roaming
1730  * between ap's on the same wired network.
1731  */
1732 static void
1733 ieee80211_deliver_l2uf(struct ieee80211_node *ni)
1734 {
1735 	struct ieee80211com *ic = ni->ni_ic;
1736 	struct ifnet *ifp = ic->ic_ifp;
1737 	struct mbuf *m;
1738 	struct l2_update_frame *l2uf;
1739 	struct ether_header *eh;
1740 
1741 	m = m_gethdr(M_NOWAIT, MT_DATA);
1742 	if (m == NULL) {
1743 		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1744 		    "%s", "no mbuf for l2uf frame");
1745 		ic->ic_stats.is_rx_nobuf++;	/* XXX not right */
1746 		return;
1747 	}
1748 	l2uf = mtod(m, struct l2_update_frame *);
1749 	eh = &l2uf->eh;
1750 	/* dst: Broadcast address */
1751 	IEEE80211_ADDR_COPY(eh->ether_dhost, ifp->if_broadcastaddr);
1752 	/* src: associated STA */
1753 	IEEE80211_ADDR_COPY(eh->ether_shost, ni->ni_macaddr);
1754 	eh->ether_type = htons(sizeof(*l2uf) - sizeof(*eh));
1755 
1756 	l2uf->dsap = 0;
1757 	l2uf->ssap = 0;
1758 	l2uf->control = 0xf5;
1759 	l2uf->xid[0] = 0x81;
1760 	l2uf->xid[1] = 0x80;
1761 	l2uf->xid[2] = 0x00;
1762 
1763 	m->m_pkthdr.len = m->m_len = sizeof(*l2uf);
1764 	ieee80211_deliver_data(ic, ni, m);
1765 }
1766 
1767 void
1768 ieee80211_recv_mgmt(struct ieee80211com *ic, struct mbuf *m0,
1769 	struct ieee80211_node *ni,
1770 	int subtype, int rssi, u_int32_t rstamp)
1771 {
1772 #define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1773 #define	ISREASSOC(_st)	((_st) == IEEE80211_FC0_SUBTYPE_REASSOC_RESP)
1774 	struct ieee80211_frame *wh;
1775 	u_int8_t *frm, *efrm;
1776 	u_int8_t *ssid, *rates, *xrates, *wpa, *wme;
1777 	int reassoc, resp, allocbs;
1778 	u_int8_t rate;
1779 
1780 	wh = mtod(m0, struct ieee80211_frame *);
1781 	frm = (u_int8_t *)&wh[1];
1782 	efrm = mtod(m0, u_int8_t *) + m0->m_len;
1783 	switch (subtype) {
1784 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1785 	case IEEE80211_FC0_SUBTYPE_BEACON: {
1786 		struct ieee80211_scanparams scan;
1787 
1788 		/*
1789 		 * We process beacon/probe response frames:
1790 		 *    o when scanning, or
1791 		 *    o station mode when associated (to collect state
1792 		 *      updates such as 802.11g slot time), or
1793 		 *    o adhoc mode (to discover neighbors)
1794 		 * Frames otherwise received are discarded.
1795 		 */
1796 		if (!((ic->ic_flags & IEEE80211_F_SCAN) ||
1797 		      (ic->ic_opmode == IEEE80211_M_STA && ni->ni_associd) ||
1798 		       ic->ic_opmode == IEEE80211_M_IBSS)) {
1799 			ic->ic_stats.is_rx_mgtdiscard++;
1800 			return;
1801 		}
1802 		/*
1803 		 * beacon/probe response frame format
1804 		 *	[8] time stamp
1805 		 *	[2] beacon interval
1806 		 *	[2] capability information
1807 		 *	[tlv] ssid
1808 		 *	[tlv] supported rates
1809 		 *	[tlv] country information
1810 		 *	[tlv] parameter set (FH/DS)
1811 		 *	[tlv] erp information
1812 		 *	[tlv] extended supported rates
1813 		 *	[tlv] WME
1814 		 *	[tlv] WPA or RSN
1815 		 */
1816 		IEEE80211_VERIFY_LENGTH(efrm - frm, 12);
1817 		memset(&scan, 0, sizeof(scan));
1818 		scan.tstamp  = frm;				frm += 8;
1819 		scan.bintval = le16toh(*(u_int16_t *)frm);	frm += 2;
1820 		scan.capinfo = le16toh(*(u_int16_t *)frm);	frm += 2;
1821 		scan.bchan = ieee80211_chan2ieee(ic, ic->ic_curchan);
1822 		scan.chan = scan.bchan;
1823 
1824 		while (efrm - frm > 1) {
1825 			IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2);
1826 			switch (*frm) {
1827 			case IEEE80211_ELEMID_SSID:
1828 				scan.ssid = frm;
1829 				break;
1830 			case IEEE80211_ELEMID_RATES:
1831 				scan.rates = frm;
1832 				break;
1833 			case IEEE80211_ELEMID_COUNTRY:
1834 				scan.country = frm;
1835 				break;
1836 			case IEEE80211_ELEMID_FHPARMS:
1837 				if (ic->ic_phytype == IEEE80211_T_FH) {
1838 					scan.fhdwell = LE_READ_2(&frm[2]);
1839 					scan.chan = IEEE80211_FH_CHAN(frm[4], frm[5]);
1840 					scan.fhindex = frm[6];
1841 				}
1842 				break;
1843 			case IEEE80211_ELEMID_DSPARMS:
1844 				/*
1845 				 * XXX hack this since depending on phytype
1846 				 * is problematic for multi-mode devices.
1847 				 */
1848 				if (ic->ic_phytype != IEEE80211_T_FH)
1849 					scan.chan = frm[2];
1850 				break;
1851 			case IEEE80211_ELEMID_TIM:
1852 				/* XXX ATIM? */
1853 				scan.tim = frm;
1854 				scan.timoff = frm - mtod(m0, u_int8_t *);
1855 				break;
1856 			case IEEE80211_ELEMID_IBSSPARMS:
1857 				break;
1858 			case IEEE80211_ELEMID_XRATES:
1859 				scan.xrates = frm;
1860 				break;
1861 			case IEEE80211_ELEMID_ERP:
1862 				if (frm[1] != 1) {
1863 					IEEE80211_DISCARD_IE(ic,
1864 					    IEEE80211_MSG_ELEMID, wh, "ERP",
1865 					    "bad len %u", frm[1]);
1866 					ic->ic_stats.is_rx_elem_toobig++;
1867 					break;
1868 				}
1869 				scan.erp = frm[2];
1870 				break;
1871 			case IEEE80211_ELEMID_RSN:
1872 				scan.wpa = frm;
1873 				break;
1874 			case IEEE80211_ELEMID_VENDOR:
1875 				if (iswpaoui(frm))
1876 					scan.wpa = frm;
1877 				else if (iswmeparam(frm) || iswmeinfo(frm))
1878 					scan.wme = frm;
1879 				/* XXX Atheros OUI support */
1880 				break;
1881 			default:
1882 				IEEE80211_DISCARD_IE(ic, IEEE80211_MSG_ELEMID,
1883 				    wh, "unhandled",
1884 				    "id %u, len %u", *frm, frm[1]);
1885 				ic->ic_stats.is_rx_elem_unknown++;
1886 				break;
1887 			}
1888 			frm += frm[1] + 2;
1889 		}
1890 		IEEE80211_VERIFY_ELEMENT(scan.rates, IEEE80211_RATE_MAXSIZE);
1891 		IEEE80211_VERIFY_ELEMENT(scan.ssid, IEEE80211_NWID_LEN);
1892 		if (
1893 #if IEEE80211_CHAN_MAX < 255
1894 		    scan.chan > IEEE80211_CHAN_MAX ||
1895 #endif
1896 		    isclr(ic->ic_chan_active, scan.chan)) {
1897 			IEEE80211_DISCARD(ic,
1898 			    IEEE80211_MSG_ELEMID | IEEE80211_MSG_INPUT,
1899 			    wh, ieee80211_mgt_subtype_name[subtype >>
1900 				IEEE80211_FC0_SUBTYPE_SHIFT],
1901 			    "invalid channel %u", scan.chan);
1902 			ic->ic_stats.is_rx_badchan++;
1903 			return;
1904 		}
1905 		if (scan.chan != scan.bchan &&
1906 		    ic->ic_phytype != IEEE80211_T_FH) {
1907 			/*
1908 			 * Frame was received on a channel different from the
1909 			 * one indicated in the DS params element id;
1910 			 * silently discard it.
1911 			 *
1912 			 * NB: this can happen due to signal leakage.
1913 			 *     But we should take it for FH phy because
1914 			 *     the rssi value should be correct even for
1915 			 *     different hop pattern in FH.
1916 			 */
1917 			IEEE80211_DISCARD(ic,
1918 			    IEEE80211_MSG_ELEMID | IEEE80211_MSG_INPUT,
1919 			    wh, ieee80211_mgt_subtype_name[subtype >>
1920 				IEEE80211_FC0_SUBTYPE_SHIFT],
1921 			    "for off-channel %u", scan.chan);
1922 			ic->ic_stats.is_rx_chanmismatch++;
1923 			return;
1924 		}
1925 		if (!(IEEE80211_BINTVAL_MIN <= scan.bintval &&
1926 		      scan.bintval <= IEEE80211_BINTVAL_MAX)) {
1927 			IEEE80211_DISCARD(ic,
1928 			    IEEE80211_MSG_ELEMID | IEEE80211_MSG_INPUT,
1929 			    wh, ieee80211_mgt_subtype_name[subtype >>
1930 				IEEE80211_FC0_SUBTYPE_SHIFT],
1931 			    "bogus beacon interval", scan.bintval);
1932 			ic->ic_stats.is_rx_badbintval++;
1933 			return;
1934 		}
1935 
1936 		/*
1937 		 * Count frame now that we know it's to be processed.
1938 		 */
1939 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
1940 			ic->ic_stats.is_rx_beacon++;		/* XXX remove */
1941 			IEEE80211_NODE_STAT(ni, rx_beacons);
1942 		} else
1943 			IEEE80211_NODE_STAT(ni, rx_proberesp);
1944 
1945 		/*
1946 		 * When operating in station mode, check for state updates.
1947 		 * Be careful to ignore beacons received while doing a
1948 		 * background scan.  We consider only 11g/WMM stuff right now.
1949 		 */
1950 		if (ic->ic_opmode == IEEE80211_M_STA &&
1951 		    ni->ni_associd != 0 &&
1952 		    ((ic->ic_flags & IEEE80211_F_SCAN) == 0 ||
1953 		     IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_bssid))) {
1954 			/* record tsf of last beacon */
1955 			memcpy(ni->ni_tstamp.data, scan.tstamp,
1956 				sizeof(ni->ni_tstamp));
1957 			/* count beacon frame for s/w bmiss handling */
1958 			ic->ic_swbmiss_count++;
1959 			ic->ic_bmiss_count = 0;
1960 			if (ni->ni_erp != scan.erp) {
1961 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1962 				    "[%s] erp change: was 0x%x, now 0x%x\n",
1963 				    ether_sprintf(wh->i_addr2),
1964 				    ni->ni_erp, scan.erp);
1965 				if (ic->ic_curmode == IEEE80211_MODE_11G &&
1966 				    (ni->ni_erp & IEEE80211_ERP_USE_PROTECTION))
1967 					ic->ic_flags |= IEEE80211_F_USEPROT;
1968 				else
1969 					ic->ic_flags &= ~IEEE80211_F_USEPROT;
1970 				ni->ni_erp = scan.erp;
1971 				/* XXX statistic */
1972 			}
1973 			if ((ni->ni_capinfo ^ scan.capinfo) & IEEE80211_CAPINFO_SHORT_SLOTTIME) {
1974 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1975 				    "[%s] capabilities change: before 0x%x,"
1976 				     " now 0x%x\n",
1977 				     ether_sprintf(wh->i_addr2),
1978 				     ni->ni_capinfo, scan.capinfo);
1979 				/*
1980 				 * NB: we assume short preamble doesn't
1981 				 *     change dynamically
1982 				 */
1983 				ieee80211_set_shortslottime(ic,
1984 					ic->ic_curmode == IEEE80211_MODE_11A ||
1985 					(scan.capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME));
1986 				ni->ni_capinfo = scan.capinfo;
1987 				/* XXX statistic */
1988 			}
1989 			if (scan.wme != NULL &&
1990 			    (ni->ni_flags & IEEE80211_NODE_QOS) &&
1991 			    ieee80211_parse_wmeparams(ic, scan.wme, wh) > 0)
1992 				ieee80211_wme_updateparams(ic);
1993 			if (scan.tim != NULL) {
1994 				struct ieee80211_tim_ie *ie =
1995 				    (struct ieee80211_tim_ie *) scan.tim;
1996 
1997 				ni->ni_dtim_count = ie->tim_count;
1998 				ni->ni_dtim_period = ie->tim_period;
1999 			}
2000 			if (ic->ic_flags & IEEE80211_F_SCAN)
2001 				ieee80211_add_scan(ic, &scan, wh,
2002 					subtype, rssi, rstamp);
2003 			return;
2004 		}
2005 		/*
2006 		 * If scanning, just pass information to the scan module.
2007 		 */
2008 		if (ic->ic_flags & IEEE80211_F_SCAN) {
2009 			if (ic->ic_flags_ext & IEEE80211_FEXT_PROBECHAN) {
2010 				/*
2011 				 * Actively scanning a channel marked passive;
2012 				 * send a probe request now that we know there
2013 				 * is 802.11 traffic present.
2014 				 *
2015 				 * XXX check if the beacon we recv'd gives
2016 				 * us what we need and suppress the probe req
2017 				 */
2018 				ieee80211_probe_curchan(ic, 1);
2019 				ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
2020 			}
2021 			ieee80211_add_scan(ic, &scan, wh,
2022 				subtype, rssi, rstamp);
2023 			return;
2024 		}
2025 		if (scan.capinfo & IEEE80211_CAPINFO_IBSS) {
2026 			if (!IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_macaddr)) {
2027 				/*
2028 				 * Create a new entry in the neighbor table.
2029 				 */
2030 				ni = ieee80211_add_neighbor(ic, wh, &scan);
2031 			} else if (ni->ni_capinfo == 0) {
2032 				/*
2033 				 * Update faked node created on transmit.
2034 				 * Note this also updates the tsf.
2035 				 */
2036 				ieee80211_init_neighbor(ni, wh, &scan);
2037 			} else {
2038 				/*
2039 				 * Record tsf for potential resync.
2040 				 */
2041 				memcpy(ni->ni_tstamp.data, scan.tstamp,
2042 					sizeof(ni->ni_tstamp));
2043 			}
2044 			if (ni != NULL) {
2045 				ni->ni_rssi = rssi;
2046 				ni->ni_rstamp = rstamp;
2047 			}
2048 		}
2049 		break;
2050 	}
2051 
2052 	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
2053 		if (ic->ic_opmode == IEEE80211_M_STA ||
2054 		    ic->ic_state != IEEE80211_S_RUN) {
2055 			ic->ic_stats.is_rx_mgtdiscard++;
2056 			return;
2057 		}
2058 		if (IEEE80211_IS_MULTICAST(wh->i_addr2)) {
2059 			/* frame must be directed */
2060 			ic->ic_stats.is_rx_mgtdiscard++;	/* XXX stat */
2061 			return;
2062 		}
2063 
2064 		/*
2065 		 * prreq frame format
2066 		 *	[tlv] ssid
2067 		 *	[tlv] supported rates
2068 		 *	[tlv] extended supported rates
2069 		 */
2070 		ssid = rates = xrates = NULL;
2071 		while (efrm - frm > 1) {
2072 			IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2);
2073 			switch (*frm) {
2074 			case IEEE80211_ELEMID_SSID:
2075 				ssid = frm;
2076 				break;
2077 			case IEEE80211_ELEMID_RATES:
2078 				rates = frm;
2079 				break;
2080 			case IEEE80211_ELEMID_XRATES:
2081 				xrates = frm;
2082 				break;
2083 			}
2084 			frm += frm[1] + 2;
2085 		}
2086 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
2087 		IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN);
2088 		IEEE80211_VERIFY_SSID(ic->ic_bss, ssid);
2089 		if ((ic->ic_flags & IEEE80211_F_HIDESSID) && ssid[1] == 0) {
2090 			IEEE80211_DISCARD(ic, IEEE80211_MSG_INPUT,
2091 			    wh, ieee80211_mgt_subtype_name[subtype >>
2092 				IEEE80211_FC0_SUBTYPE_SHIFT],
2093 			    "%s", "no ssid with ssid suppression enabled");
2094 			ic->ic_stats.is_rx_ssidmismatch++; /*XXX*/
2095 			return;
2096 		}
2097 
2098 		allocbs = 0;
2099 		if (ni == ic->ic_bss) {
2100 			if (ic->ic_opmode != IEEE80211_M_IBSS) {
2101 				ni = ieee80211_tmp_node(ic, wh->i_addr2);
2102 				allocbs = 1;
2103 			} else if (!IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_macaddr)) {
2104 				/*
2105 				 * XXX Cannot tell if the sender is operating
2106 				 * in ibss mode.  But we need a new node to
2107 				 * send the response so blindly add them to the
2108 				 * neighbor table.
2109 				 */
2110 				ni = ieee80211_fakeup_adhoc_node(&ic->ic_sta,
2111 					wh->i_addr2);
2112 			}
2113 			if (ni == NULL)
2114 				return;
2115 		}
2116 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2117 		    "[%s] recv probe req\n", ether_sprintf(wh->i_addr2));
2118 		ni->ni_rssi = rssi;
2119 		ni->ni_rstamp = rstamp;
2120 		rate = ieee80211_setup_rates(ni, rates, xrates,
2121 			  IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE
2122 			| IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2123 		if (rate & IEEE80211_RATE_BASIC) {
2124 			IEEE80211_DISCARD(ic, IEEE80211_MSG_XRATE,
2125 			    wh, ieee80211_mgt_subtype_name[subtype >>
2126 				IEEE80211_FC0_SUBTYPE_SHIFT],
2127 			    "%s", "recv'd rate set invalid");
2128 		} else {
2129 			IEEE80211_SEND_MGMT(ic, ni,
2130 				IEEE80211_FC0_SUBTYPE_PROBE_RESP, 0);
2131 		}
2132 		if (allocbs) {
2133 			/*
2134 			 * Temporary node created just to send a
2135 			 * response, reclaim immediately.
2136 			 */
2137 			ieee80211_free_node(ni);
2138 		}
2139 		break;
2140 
2141 	case IEEE80211_FC0_SUBTYPE_AUTH: {
2142 		u_int16_t algo, seq, status;
2143 		/*
2144 		 * auth frame format
2145 		 *	[2] algorithm
2146 		 *	[2] sequence
2147 		 *	[2] status
2148 		 *	[tlv*] challenge
2149 		 */
2150 		IEEE80211_VERIFY_LENGTH(efrm - frm, 6);
2151 		algo   = le16toh(*(u_int16_t *)frm);
2152 		seq    = le16toh(*(u_int16_t *)(frm + 2));
2153 		status = le16toh(*(u_int16_t *)(frm + 4));
2154 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
2155 		    "[%s] recv auth frame with algorithm %d seq %d\n",
2156 		    ether_sprintf(wh->i_addr2), algo, seq);
2157 		/*
2158 		 * Consult the ACL policy module if setup.
2159 		 */
2160 		if (ic->ic_acl != NULL &&
2161 		    !ic->ic_acl->iac_check(ic, wh->i_addr2)) {
2162 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ACL,
2163 			    wh, "auth", "%s", "disallowed by ACL");
2164 			ic->ic_stats.is_rx_acl++;
2165 			if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2166 				IEEE80211_SEND_MGMT(ic, ni,
2167 				    IEEE80211_FC0_SUBTYPE_AUTH,
2168 				    (seq+1) | (IEEE80211_STATUS_UNSPECIFIED<<16));
2169 			}
2170 			return;
2171 		}
2172 		if (ic->ic_flags & IEEE80211_F_COUNTERM) {
2173 			IEEE80211_DISCARD(ic,
2174 			    IEEE80211_MSG_AUTH | IEEE80211_MSG_CRYPTO,
2175 			    wh, "auth", "%s", "TKIP countermeasures enabled");
2176 			ic->ic_stats.is_rx_auth_countermeasures++;
2177 			if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2178 				IEEE80211_SEND_MGMT(ic, ni,
2179 					IEEE80211_FC0_SUBTYPE_AUTH,
2180 					IEEE80211_REASON_MIC_FAILURE);
2181 			}
2182 			return;
2183 		}
2184 		if (algo == IEEE80211_AUTH_ALG_SHARED)
2185 			ieee80211_auth_shared(ic, wh, frm + 6, efrm, ni, rssi,
2186 			    rstamp, seq, status);
2187 		else if (algo == IEEE80211_AUTH_ALG_OPEN)
2188 			ieee80211_auth_open(ic, wh, ni, rssi, rstamp, seq,
2189 			    status);
2190 		else {
2191 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
2192 			    wh, "auth", "unsupported alg %d", algo);
2193 			ic->ic_stats.is_rx_auth_unsupported++;
2194 			if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2195 				/* XXX not right */
2196 				IEEE80211_SEND_MGMT(ic, ni,
2197 					IEEE80211_FC0_SUBTYPE_AUTH,
2198 					(seq+1) | (IEEE80211_STATUS_ALG<<16));
2199 			}
2200 			return;
2201 		}
2202 		break;
2203 	}
2204 
2205 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
2206 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ: {
2207 		u_int16_t capinfo, lintval;
2208 		struct ieee80211_rsnparms rsn;
2209 		u_int8_t reason;
2210 
2211 		if (ic->ic_opmode != IEEE80211_M_HOSTAP ||
2212 		    ic->ic_state != IEEE80211_S_RUN) {
2213 			ic->ic_stats.is_rx_mgtdiscard++;
2214 			return;
2215 		}
2216 
2217 		if (subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
2218 			reassoc = 1;
2219 			resp = IEEE80211_FC0_SUBTYPE_REASSOC_RESP;
2220 		} else {
2221 			reassoc = 0;
2222 			resp = IEEE80211_FC0_SUBTYPE_ASSOC_RESP;
2223 		}
2224 		/*
2225 		 * asreq frame format
2226 		 *	[2] capability information
2227 		 *	[2] listen interval
2228 		 *	[6*] current AP address (reassoc only)
2229 		 *	[tlv] ssid
2230 		 *	[tlv] supported rates
2231 		 *	[tlv] extended supported rates
2232 		 *	[tlv] WPA or RSN
2233 		 */
2234 		IEEE80211_VERIFY_LENGTH(efrm - frm, (reassoc ? 10 : 4));
2235 		if (!IEEE80211_ADDR_EQ(wh->i_addr3, ic->ic_bss->ni_bssid)) {
2236 			IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
2237 			    wh, ieee80211_mgt_subtype_name[subtype >>
2238 				IEEE80211_FC0_SUBTYPE_SHIFT],
2239 			    "%s", "wrong bssid");
2240 			ic->ic_stats.is_rx_assoc_bss++;
2241 			return;
2242 		}
2243 		capinfo = le16toh(*(u_int16_t *)frm);	frm += 2;
2244 		lintval = le16toh(*(u_int16_t *)frm);	frm += 2;
2245 		if (reassoc)
2246 			frm += 6;	/* ignore current AP info */
2247 		ssid = rates = xrates = wpa = wme = NULL;
2248 		while (efrm - frm > 1) {
2249 			IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2);
2250 			switch (*frm) {
2251 			case IEEE80211_ELEMID_SSID:
2252 				ssid = frm;
2253 				break;
2254 			case IEEE80211_ELEMID_RATES:
2255 				rates = frm;
2256 				break;
2257 			case IEEE80211_ELEMID_XRATES:
2258 				xrates = frm;
2259 				break;
2260 			/* XXX verify only one of RSN and WPA ie's? */
2261 			case IEEE80211_ELEMID_RSN:
2262 				wpa = frm;
2263 				break;
2264 			case IEEE80211_ELEMID_VENDOR:
2265 				if (iswpaoui(frm))
2266 					wpa = frm;
2267 				else if (iswmeinfo(frm))
2268 					wme = frm;
2269 				/* XXX Atheros OUI support */
2270 				break;
2271 			}
2272 			frm += frm[1] + 2;
2273 		}
2274 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
2275 		IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN);
2276 		IEEE80211_VERIFY_SSID(ic->ic_bss, ssid);
2277 
2278 		if (ni == ic->ic_bss) {
2279 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2280 			    "[%s] deny %s request, sta not authenticated\n",
2281 			    ether_sprintf(wh->i_addr2),
2282 			    reassoc ? "reassoc" : "assoc");
2283 			ieee80211_send_error(ic, ni, wh->i_addr2,
2284 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2285 			    IEEE80211_REASON_ASSOC_NOT_AUTHED);
2286 			ic->ic_stats.is_rx_assoc_notauth++;
2287 			return;
2288 		}
2289 		/* assert right associstion security credentials */
2290 		if (wpa == NULL && (ic->ic_flags & IEEE80211_F_WPA)) {
2291 			IEEE80211_DPRINTF(ic,
2292 			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_WPA,
2293 			    "[%s] no WPA/RSN IE in association request\n",
2294 			    ether_sprintf(wh->i_addr2));
2295 			IEEE80211_SEND_MGMT(ic, ni,
2296 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2297 			    IEEE80211_REASON_RSN_REQUIRED);
2298 			ieee80211_node_leave(ic, ni);
2299 			/* XXX distinguish WPA/RSN? */
2300 			ic->ic_stats.is_rx_assoc_badwpaie++;
2301 			return;
2302 		}
2303 		if (wpa != NULL) {
2304 			/*
2305 			 * Parse WPA information element.  Note that
2306 			 * we initialize the param block from the node
2307 			 * state so that information in the IE overrides
2308 			 * our defaults.  The resulting parameters are
2309 			 * installed below after the association is assured.
2310 			 */
2311 			rsn = ni->ni_rsn;
2312 			if (wpa[0] != IEEE80211_ELEMID_RSN)
2313 				reason = ieee80211_parse_wpa(ic, wpa, &rsn, wh);
2314 			else
2315 				reason = ieee80211_parse_rsn(ic, wpa, &rsn, wh);
2316 			if (reason != 0) {
2317 				IEEE80211_SEND_MGMT(ic, ni,
2318 				    IEEE80211_FC0_SUBTYPE_DEAUTH, reason);
2319 				ieee80211_node_leave(ic, ni);
2320 				/* XXX distinguish WPA/RSN? */
2321 				ic->ic_stats.is_rx_assoc_badwpaie++;
2322 				return;
2323 			}
2324 			IEEE80211_DPRINTF(ic,
2325 			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_WPA,
2326 			    "[%s] %s ie: mc %u/%u uc %u/%u key %u caps 0x%x\n",
2327 			    ether_sprintf(wh->i_addr2),
2328 			    wpa[0] != IEEE80211_ELEMID_RSN ?  "WPA" : "RSN",
2329 			    rsn.rsn_mcastcipher, rsn.rsn_mcastkeylen,
2330 			    rsn.rsn_ucastcipher, rsn.rsn_ucastkeylen,
2331 			    rsn.rsn_keymgmt, rsn.rsn_caps);
2332 		}
2333 		/* discard challenge after association */
2334 		if (ni->ni_challenge != NULL) {
2335 			FREE(ni->ni_challenge, M_DEVBUF);
2336 			ni->ni_challenge = NULL;
2337 		}
2338 		/* NB: 802.11 spec says to ignore station's privacy bit */
2339 		if ((capinfo & IEEE80211_CAPINFO_ESS) == 0) {
2340 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2341 			    "[%s] deny %s request, capability mismatch 0x%x\n",
2342 			    ether_sprintf(wh->i_addr2),
2343 			    reassoc ? "reassoc" : "assoc", capinfo);
2344 			IEEE80211_SEND_MGMT(ic, ni, resp,
2345 				IEEE80211_STATUS_CAPINFO);
2346 			ieee80211_node_leave(ic, ni);
2347 			ic->ic_stats.is_rx_assoc_capmismatch++;
2348 			return;
2349 		}
2350 		rate = ieee80211_setup_rates(ni, rates, xrates,
2351 				IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
2352 				IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2353 		/*
2354 		 * If constrained to 11g-only stations reject an
2355 		 * 11b-only station.  We cheat a bit here by looking
2356 		 * at the max negotiated xmit rate and assuming anyone
2357 		 * with a best rate <24Mb/s is an 11b station.
2358 		 */
2359 		if ((rate & IEEE80211_RATE_BASIC) ||
2360 		    ((ic->ic_flags & IEEE80211_F_PUREG) && rate < 48)) {
2361 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2362 			    "[%s] deny %s request, rate set mismatch\n",
2363 			    ether_sprintf(wh->i_addr2),
2364 			    reassoc ? "reassoc" : "assoc");
2365 			IEEE80211_SEND_MGMT(ic, ni, resp,
2366 				IEEE80211_STATUS_BASIC_RATE);
2367 			ieee80211_node_leave(ic, ni);
2368 			ic->ic_stats.is_rx_assoc_norate++;
2369 			return;
2370 		}
2371 		ni->ni_rssi = rssi;
2372 		ni->ni_rstamp = rstamp;
2373 		ni->ni_intval = lintval;
2374 		ni->ni_capinfo = capinfo;
2375 		ni->ni_chan = ic->ic_bss->ni_chan;
2376 		ni->ni_fhdwell = ic->ic_bss->ni_fhdwell;
2377 		ni->ni_fhindex = ic->ic_bss->ni_fhindex;
2378 		if (wpa != NULL) {
2379 			/*
2380 			 * Record WPA/RSN parameters for station, mark
2381 			 * node as using WPA and record information element
2382 			 * for applications that require it.
2383 			 */
2384 			ni->ni_rsn = rsn;
2385 			ieee80211_saveie(&ni->ni_wpa_ie, wpa);
2386 		} else if (ni->ni_wpa_ie != NULL) {
2387 			/*
2388 			 * Flush any state from a previous association.
2389 			 */
2390 			FREE(ni->ni_wpa_ie, M_DEVBUF);
2391 			ni->ni_wpa_ie = NULL;
2392 		}
2393 		if (wme != NULL) {
2394 			/*
2395 			 * Record WME parameters for station, mark node
2396 			 * as capable of QoS and record information
2397 			 * element for applications that require it.
2398 			 */
2399 			ieee80211_saveie(&ni->ni_wme_ie, wme);
2400 			ni->ni_flags |= IEEE80211_NODE_QOS;
2401 		} else if (ni->ni_wme_ie != NULL) {
2402 			/*
2403 			 * Flush any state from a previous association.
2404 			 */
2405 			FREE(ni->ni_wme_ie, M_DEVBUF);
2406 			ni->ni_wme_ie = NULL;
2407 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
2408 		}
2409 		ieee80211_deliver_l2uf(ni);
2410 		ieee80211_node_join(ic, ni, resp);
2411 		break;
2412 	}
2413 
2414 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
2415 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP: {
2416 		u_int16_t capinfo, associd;
2417 		u_int16_t status;
2418 
2419 		if (ic->ic_opmode != IEEE80211_M_STA ||
2420 		    ic->ic_state != IEEE80211_S_ASSOC) {
2421 			ic->ic_stats.is_rx_mgtdiscard++;
2422 			return;
2423 		}
2424 
2425 		/*
2426 		 * asresp frame format
2427 		 *	[2] capability information
2428 		 *	[2] status
2429 		 *	[2] association ID
2430 		 *	[tlv] supported rates
2431 		 *	[tlv] extended supported rates
2432 		 *	[tlv] WME
2433 		 */
2434 		IEEE80211_VERIFY_LENGTH(efrm - frm, 6);
2435 		ni = ic->ic_bss;
2436 		capinfo = le16toh(*(u_int16_t *)frm);
2437 		frm += 2;
2438 		status = le16toh(*(u_int16_t *)frm);
2439 		frm += 2;
2440 		if (status != 0) {
2441 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2442 			    "[%s] %sassoc failed (reason %d)\n",
2443 			    ether_sprintf(wh->i_addr2),
2444 			    ISREASSOC(subtype) ?  "re" : "", status);
2445 			if (ni != ic->ic_bss)	/* XXX never true? */
2446 				ni->ni_fails++;
2447 			ic->ic_stats.is_rx_auth_fail++;	/* XXX */
2448 			return;
2449 		}
2450 		associd = le16toh(*(u_int16_t *)frm);
2451 		frm += 2;
2452 
2453 		rates = xrates = wpa = wme = NULL;
2454 		while (efrm - frm > 1) {
2455 			IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2);
2456 			switch (*frm) {
2457 			case IEEE80211_ELEMID_RATES:
2458 				rates = frm;
2459 				break;
2460 			case IEEE80211_ELEMID_XRATES:
2461 				xrates = frm;
2462 				break;
2463 			case IEEE80211_ELEMID_VENDOR:
2464 				if (iswmeoui(frm))
2465 					wme = frm;
2466 				/* XXX Atheros OUI support */
2467 				break;
2468 			}
2469 			frm += frm[1] + 2;
2470 		}
2471 
2472 		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE);
2473 		rate = ieee80211_setup_rates(ni, rates, xrates,
2474 				IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
2475 				IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2476 		if (rate & IEEE80211_RATE_BASIC) {
2477 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2478 			    "[%s] %sassoc failed (rate set mismatch)\n",
2479 			    ether_sprintf(wh->i_addr2),
2480 			    ISREASSOC(subtype) ?  "re" : "");
2481 			if (ni != ic->ic_bss)	/* XXX never true? */
2482 				ni->ni_fails++;
2483 			ic->ic_stats.is_rx_assoc_norate++;
2484 			ieee80211_new_state(ic, IEEE80211_S_SCAN, 0);
2485 			return;
2486 		}
2487 
2488 		ni->ni_capinfo = capinfo;
2489 		ni->ni_associd = associd;
2490 		if (wme != NULL &&
2491 		    ieee80211_parse_wmeparams(ic, wme, wh) >= 0) {
2492 			ni->ni_flags |= IEEE80211_NODE_QOS;
2493 			ieee80211_wme_updateparams(ic);
2494 		} else
2495 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
2496 		/*
2497 		 * Configure state now that we are associated.
2498 		 *
2499 		 * XXX may need different/additional driver callbacks?
2500 		 */
2501 		if (ic->ic_curmode == IEEE80211_MODE_11A ||
2502 		    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
2503 			ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2504 			ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2505 		} else {
2506 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2507 			ic->ic_flags |= IEEE80211_F_USEBARKER;
2508 		}
2509 		ieee80211_set_shortslottime(ic,
2510 			ic->ic_curmode == IEEE80211_MODE_11A ||
2511 			(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME));
2512 		/*
2513 		 * Honor ERP protection.
2514 		 *
2515 		 * NB: ni_erp should zero for non-11g operation.
2516 		 * XXX check ic_curmode anyway?
2517 		 */
2518 		if (ic->ic_curmode == IEEE80211_MODE_11G &&
2519 		    (ni->ni_erp & IEEE80211_ERP_USE_PROTECTION))
2520 			ic->ic_flags |= IEEE80211_F_USEPROT;
2521 		else
2522 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2523 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2524 		    "[%s] %sassoc success: %s preamble, %s slot time%s%s\n",
2525 		    ether_sprintf(wh->i_addr2),
2526 		    ISREASSOC(subtype) ? "re" : "",
2527 		    ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
2528 		    ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
2529 		    ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : "",
2530 		    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2531 		);
2532 		ieee80211_new_state(ic, IEEE80211_S_RUN, subtype);
2533 		break;
2534 	}
2535 
2536 	case IEEE80211_FC0_SUBTYPE_DEAUTH: {
2537 		u_int16_t reason;
2538 
2539 		if (ic->ic_state == IEEE80211_S_SCAN) {
2540 			ic->ic_stats.is_rx_mgtdiscard++;
2541 			return;
2542 		}
2543 		/*
2544 		 * deauth frame format
2545 		 *	[2] reason
2546 		 */
2547 		IEEE80211_VERIFY_LENGTH(efrm - frm, 2);
2548 		reason = le16toh(*(u_int16_t *)frm);
2549 		ic->ic_stats.is_rx_deauth++;
2550 		IEEE80211_NODE_STAT(ni, rx_deauth);
2551 
2552 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
2553 		    "[%s] recv deauthenticate (reason %d)\n",
2554 		    ether_sprintf(ni->ni_macaddr), reason);
2555 		switch (ic->ic_opmode) {
2556 		case IEEE80211_M_STA:
2557 			ieee80211_new_state(ic, IEEE80211_S_AUTH,
2558 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2559 			break;
2560 		case IEEE80211_M_HOSTAP:
2561 			if (ni != ic->ic_bss)
2562 				ieee80211_node_leave(ic, ni);
2563 			break;
2564 		default:
2565 			ic->ic_stats.is_rx_mgtdiscard++;
2566 			break;
2567 		}
2568 		break;
2569 	}
2570 
2571 	case IEEE80211_FC0_SUBTYPE_DISASSOC: {
2572 		u_int16_t reason;
2573 
2574 		if (ic->ic_state != IEEE80211_S_RUN &&
2575 		    ic->ic_state != IEEE80211_S_ASSOC &&
2576 		    ic->ic_state != IEEE80211_S_AUTH) {
2577 			ic->ic_stats.is_rx_mgtdiscard++;
2578 			return;
2579 		}
2580 		/*
2581 		 * disassoc frame format
2582 		 *	[2] reason
2583 		 */
2584 		IEEE80211_VERIFY_LENGTH(efrm - frm, 2);
2585 		reason = le16toh(*(u_int16_t *)frm);
2586 		ic->ic_stats.is_rx_disassoc++;
2587 		IEEE80211_NODE_STAT(ni, rx_disassoc);
2588 
2589 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2590 		    "[%s] recv disassociate (reason %d)\n",
2591 		    ether_sprintf(ni->ni_macaddr), reason);
2592 		switch (ic->ic_opmode) {
2593 		case IEEE80211_M_STA:
2594 			ieee80211_new_state(ic, IEEE80211_S_ASSOC,
2595 			    wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK);
2596 			break;
2597 		case IEEE80211_M_HOSTAP:
2598 			if (ni != ic->ic_bss)
2599 				ieee80211_node_leave(ic, ni);
2600 			break;
2601 		default:
2602 			ic->ic_stats.is_rx_mgtdiscard++;
2603 			break;
2604 		}
2605 		break;
2606 	}
2607 	default:
2608 		IEEE80211_DISCARD(ic, IEEE80211_MSG_ANY,
2609 		     wh, "mgt", "subtype 0x%x not handled", subtype);
2610 		ic->ic_stats.is_rx_badsubtype++;
2611 		break;
2612 	}
2613 #undef ISREASSOC
2614 #undef ISPROBE
2615 }
2616 #undef IEEE80211_VERIFY_LENGTH
2617 #undef IEEE80211_VERIFY_ELEMENT
2618 
2619 /*
2620  * Handle station power-save state change.
2621  */
2622 static void
2623 ieee80211_node_pwrsave(struct ieee80211_node *ni, int enable)
2624 {
2625 	struct ieee80211com *ic = ni->ni_ic;
2626 	struct mbuf *m;
2627 
2628 	if (enable) {
2629 		if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) == 0)
2630 			ic->ic_ps_sta++;
2631 		ni->ni_flags |= IEEE80211_NODE_PWR_MGT;
2632 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2633 		    "[%s] power save mode on, %u sta's in ps mode\n",
2634 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
2635 		return;
2636 	}
2637 
2638 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT)
2639 		ic->ic_ps_sta--;
2640 	ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
2641 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2642 	    "[%s] power save mode off, %u sta's in ps mode\n",
2643 	    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
2644 	/* XXX if no stations in ps mode, flush mc frames */
2645 
2646 	/*
2647 	 * Flush queued unicast frames.
2648 	 */
2649 	if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0) {
2650 		if (ic->ic_set_tim != NULL)
2651 			ic->ic_set_tim(ni, 0);		/* just in case */
2652 		return;
2653 	}
2654 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2655 	    "[%s] flush ps queue, %u packets queued\n",
2656 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_SAVEQ_QLEN(ni));
2657 	for (;;) {
2658 		int qlen;
2659 
2660 		IEEE80211_NODE_SAVEQ_DEQUEUE(ni, m, qlen);
2661 		if (m == NULL)
2662 			break;
2663 		/*
2664 		 * If this is the last packet, turn off the TIM bit.
2665 		 * If there are more packets, set the more packets bit
2666 		 * in the mbuf so ieee80211_encap will mark the 802.11
2667 		 * head to indicate more data frames will follow.
2668 		 */
2669 		if (qlen != 0)
2670 			m->m_flags |= M_MORE_DATA;
2671 		/* XXX need different driver interface */
2672 		/* XXX bypasses q max */
2673 		IF_ENQUEUE(&ic->ic_ifp->if_snd, m);
2674 	}
2675 	if (ic->ic_set_tim != NULL)
2676 		ic->ic_set_tim(ni, 0);
2677 }
2678 
2679 /*
2680  * Process a received ps-poll frame.
2681  */
2682 static void
2683 ieee80211_recv_pspoll(struct ieee80211com *ic,
2684 	struct ieee80211_node *ni, struct mbuf *m0)
2685 {
2686 	struct ieee80211_frame_min *wh;
2687 	struct mbuf *m;
2688 	u_int16_t aid;
2689 	int qlen;
2690 
2691 	wh = mtod(m0, struct ieee80211_frame_min *);
2692 	if (ni->ni_associd == 0) {
2693 		IEEE80211_DISCARD(ic, IEEE80211_MSG_POWER | IEEE80211_MSG_DEBUG,
2694 		    (struct ieee80211_frame *) wh, "ps-poll",
2695 		    "%s", "unassociated station");
2696 		ic->ic_stats.is_ps_unassoc++;
2697 		IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_DEAUTH,
2698 			IEEE80211_REASON_NOT_ASSOCED);
2699 		return;
2700 	}
2701 
2702 	aid = le16toh(*(u_int16_t *)wh->i_dur);
2703 	if (aid != ni->ni_associd) {
2704 		IEEE80211_DISCARD(ic, IEEE80211_MSG_POWER | IEEE80211_MSG_DEBUG,
2705 		    (struct ieee80211_frame *) wh, "ps-poll",
2706 		    "aid mismatch: sta aid 0x%x poll aid 0x%x",
2707 		    ni->ni_associd, aid);
2708 		ic->ic_stats.is_ps_badaid++;
2709 		IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_DEAUTH,
2710 			IEEE80211_REASON_NOT_ASSOCED);
2711 		return;
2712 	}
2713 
2714 	/* Okay, take the first queued packet and put it out... */
2715 	IEEE80211_NODE_SAVEQ_DEQUEUE(ni, m, qlen);
2716 	if (m == NULL) {
2717 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2718 		    "[%s] recv ps-poll, but queue empty\n",
2719 		    ether_sprintf(wh->i_addr2));
2720 		ieee80211_send_nulldata(ieee80211_ref_node(ni));
2721 		ic->ic_stats.is_ps_qempty++;	/* XXX node stat */
2722 		if (ic->ic_set_tim != NULL)
2723 			ic->ic_set_tim(ni, 0);	/* just in case */
2724 		return;
2725 	}
2726 	/*
2727 	 * If there are more packets, set the more packets bit
2728 	 * in the packet dispatched to the station; otherwise
2729 	 * turn off the TIM bit.
2730 	 */
2731 	if (qlen != 0) {
2732 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2733 		    "[%s] recv ps-poll, send packet, %u still queued\n",
2734 		    ether_sprintf(ni->ni_macaddr), qlen);
2735 		m->m_flags |= M_MORE_DATA;
2736 	} else {
2737 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2738 		    "[%s] recv ps-poll, send packet, queue empty\n",
2739 		    ether_sprintf(ni->ni_macaddr));
2740 		if (ic->ic_set_tim != NULL)
2741 			ic->ic_set_tim(ni, 0);
2742 	}
2743 	m->m_flags |= M_PWR_SAV;		/* bypass PS handling */
2744 	IF_ENQUEUE(&ic->ic_ifp->if_snd, m);
2745 }
2746 
2747 #ifdef IEEE80211_DEBUG
2748 /*
2749  * Debugging support.
2750  */
2751 
2752 /*
2753  * Return the bssid of a frame.
2754  */
2755 static const u_int8_t *
2756 ieee80211_getbssid(struct ieee80211com *ic, const struct ieee80211_frame *wh)
2757 {
2758 	if (ic->ic_opmode == IEEE80211_M_STA)
2759 		return wh->i_addr2;
2760 	if ((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_NODS)
2761 		return wh->i_addr1;
2762 	if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
2763 		return wh->i_addr1;
2764 	return wh->i_addr3;
2765 }
2766 
2767 void
2768 ieee80211_note(struct ieee80211com *ic, const char *fmt, ...)
2769 {
2770 	char buf[128];		/* XXX */
2771 	va_list ap;
2772 
2773 	va_start(ap, fmt);
2774 	vsnprintf(buf, sizeof(buf), fmt, ap);
2775 	va_end(ap);
2776 
2777 	if_printf(ic->ic_ifp, "%s", buf);	/* NB: no \n */
2778 }
2779 
2780 void
2781 ieee80211_note_frame(struct ieee80211com *ic,
2782 	const struct ieee80211_frame *wh,
2783 	const char *fmt, ...)
2784 {
2785 	char buf[128];		/* XXX */
2786 	va_list ap;
2787 
2788 	va_start(ap, fmt);
2789 	vsnprintf(buf, sizeof(buf), fmt, ap);
2790 	va_end(ap);
2791 	if_printf(ic->ic_ifp, "[%s] %s\n",
2792 		ether_sprintf(ieee80211_getbssid(ic, wh)), buf);
2793 }
2794 
2795 void
2796 ieee80211_note_mac(struct ieee80211com *ic,
2797 	const u_int8_t mac[IEEE80211_ADDR_LEN],
2798 	const char *fmt, ...)
2799 {
2800 	char buf[128];		/* XXX */
2801 	va_list ap;
2802 
2803 	va_start(ap, fmt);
2804 	vsnprintf(buf, sizeof(buf), fmt, ap);
2805 	va_end(ap);
2806 	if_printf(ic->ic_ifp, "[%s] %s\n", ether_sprintf(mac), buf);
2807 }
2808 
2809 static void
2810 ieee80211_discard_frame(struct ieee80211com *ic,
2811 	const struct ieee80211_frame *wh,
2812 	const char *type, const char *fmt, ...)
2813 {
2814 	va_list ap;
2815 
2816 	printf("[%s:%s] discard ", ic->ic_ifp->if_xname,
2817 		ether_sprintf(ieee80211_getbssid(ic, wh)));
2818 	if (type != NULL)
2819 		printf("%s frame, ", type);
2820 	else
2821 		printf("frame, ");
2822 	va_start(ap, fmt);
2823 	vprintf(fmt, ap);
2824 	va_end(ap);
2825 	printf("\n");
2826 }
2827 
2828 static void
2829 ieee80211_discard_ie(struct ieee80211com *ic,
2830 	const struct ieee80211_frame *wh,
2831 	const char *type, const char *fmt, ...)
2832 {
2833 	va_list ap;
2834 
2835 	printf("[%s:%s] discard ", ic->ic_ifp->if_xname,
2836 		ether_sprintf(ieee80211_getbssid(ic, wh)));
2837 	if (type != NULL)
2838 		printf("%s information element, ", type);
2839 	else
2840 		printf("information element, ");
2841 	va_start(ap, fmt);
2842 	vprintf(fmt, ap);
2843 	va_end(ap);
2844 	printf("\n");
2845 }
2846 
2847 static void
2848 ieee80211_discard_mac(struct ieee80211com *ic,
2849 	const u_int8_t mac[IEEE80211_ADDR_LEN],
2850 	const char *type, const char *fmt, ...)
2851 {
2852 	va_list ap;
2853 
2854 	printf("[%s:%s] discard ", ic->ic_ifp->if_xname, ether_sprintf(mac));
2855 	if (type != NULL)
2856 		printf("%s frame, ", type);
2857 	else
2858 		printf("frame, ");
2859 	va_start(ap, fmt);
2860 	vprintf(fmt, ap);
2861 	va_end(ap);
2862 	printf("\n");
2863 }
2864 #endif /* IEEE80211_DEBUG */
2865