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