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