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