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