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