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