ieee80211_output.c revision 138609
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2004 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_output.c 138609 2004-12-08 22:34:07Z sam $");
35
36#include "opt_inet.h"
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/mbuf.h>
41#include <sys/kernel.h>
42#include <sys/endian.h>
43
44#include <sys/socket.h>
45
46#include <net/bpf.h>
47#include <net/ethernet.h>
48#include <net/if.h>
49#include <net/if_llc.h>
50#include <net/if_media.h>
51#include <net/if_vlan_var.h>
52
53#include <net80211/ieee80211_var.h>
54
55#ifdef INET
56#include <netinet/in.h>
57#include <netinet/if_ether.h>
58#include <netinet/in_systm.h>
59#include <netinet/ip.h>
60#endif
61
62#ifdef IEEE80211_DEBUG
63/*
64 * Decide if an outbound management frame should be
65 * printed when debugging is enabled.  This filters some
66 * of the less interesting frames that come frequently
67 * (e.g. beacons).
68 */
69static __inline int
70doprint(struct ieee80211com *ic, int subtype)
71{
72	switch (subtype) {
73	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
74		return (ic->ic_opmode == IEEE80211_M_IBSS);
75	}
76	return 1;
77}
78#endif
79
80/*
81 * Send a management frame to the specified node.  The node pointer
82 * must have a reference as the pointer will be passed to the driver
83 * and potentially held for a long time.  If the frame is successfully
84 * dispatched to the driver, then it is responsible for freeing the
85 * reference (and potentially free'ing up any associated storage).
86 */
87static int
88ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
89    struct mbuf *m, int type)
90{
91	struct ifnet *ifp = ic->ic_ifp;
92	struct ieee80211_frame *wh;
93
94	KASSERT(ni != NULL, ("null node"));
95
96	/*
97	 * Yech, hack alert!  We want to pass the node down to the
98	 * driver's start routine.  If we don't do so then the start
99	 * routine must immediately look it up again and that can
100	 * cause a lock order reversal if, for example, this frame
101	 * is being sent because the station is being timedout and
102	 * the frame being sent is a DEAUTH message.  We could stick
103	 * this in an m_tag and tack that on to the mbuf.  However
104	 * that's rather expensive to do for every frame so instead
105	 * we stuff it in the rcvif field since outbound frames do
106	 * not (presently) use this.
107	 */
108	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
109	if (m == NULL)
110		return ENOMEM;
111	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
112	m->m_pkthdr.rcvif = (void *)ni;
113
114	wh = mtod(m, struct ieee80211_frame *);
115	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT | type;
116	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
117	*(u_int16_t *)wh->i_dur = 0;
118	*(u_int16_t *)wh->i_seq =
119	    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
120	ni->ni_txseqs[0]++;
121	/*
122	 * Hack.  When sending PROBE_REQ frames while scanning we
123	 * explicitly force a broadcast rather than (as before) clobber
124	 * ni_macaddr and ni_bssid.  This is stopgap, we need a way
125	 * to communicate this directly rather than do something
126	 * implicit based on surrounding state.
127	 */
128	if (type == IEEE80211_FC0_SUBTYPE_PROBE_REQ &&
129	    (ic->ic_flags & IEEE80211_F_SCAN)) {
130		IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
131		IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
132		IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
133	} else {
134		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr);
135		IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
136		IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
137	}
138
139	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
140		m->m_flags &= ~M_LINK0;
141		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
142			"[%s] encrypting frame (%s)\n",
143			ether_sprintf(wh->i_addr1), __func__);
144		wh->i_fc[1] |= IEEE80211_FC1_WEP;
145	}
146#ifdef IEEE80211_DEBUG
147	/* avoid printing too many frames */
148	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
149	    ieee80211_msg_dumppkts(ic)) {
150		printf("[%s] send %s on channel %u\n",
151		    ether_sprintf(wh->i_addr1),
152		    ieee80211_mgt_subtype_name[
153			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
154				IEEE80211_FC0_SUBTYPE_SHIFT],
155		    ieee80211_chan2ieee(ic, ni->ni_chan));
156	}
157#endif
158	IEEE80211_NODE_STAT(ni, tx_mgmt);
159	IF_ENQUEUE(&ic->ic_mgtq, m);
160	ifp->if_timer = 1;
161	if_start(ifp);
162	return 0;
163}
164
165/*
166 * Send a null data frame to the specified node.
167 */
168int
169ieee80211_send_nulldata(struct ieee80211com *ic, struct ieee80211_node *ni)
170{
171	struct ifnet *ifp = ic->ic_ifp;
172	struct mbuf *m;
173	struct ieee80211_frame *wh;
174
175	MGETHDR(m, M_NOWAIT, MT_HEADER);
176	if (m == NULL) {
177		/* XXX debug msg */
178		ic->ic_stats.is_tx_nobuf++;
179		return ENOMEM;
180	}
181	m->m_pkthdr.rcvif = (void *) ieee80211_ref_node(ni);
182
183	wh = mtod(m, struct ieee80211_frame *);
184	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA |
185		IEEE80211_FC0_SUBTYPE_NODATA;
186	*(u_int16_t *)wh->i_dur = 0;
187	*(u_int16_t *)wh->i_seq =
188	    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
189	ni->ni_txseqs[0]++;
190
191	/* XXX WDS */
192	wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
193	IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr);
194	IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
195	IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_myaddr);
196	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
197
198	IEEE80211_NODE_STAT(ni, tx_data);
199
200	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
201	if_start(ifp);
202
203	return 0;
204}
205
206/*
207 * Insure there is sufficient contiguous space to encapsulate the
208 * 802.11 data frame.  If room isn't already there, arrange for it.
209 * Drivers and cipher modules assume we have done the necessary work
210 * and fail rudely if they don't find the space they need.
211 */
212static struct mbuf *
213ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
214	struct ieee80211_key *key, struct mbuf *m)
215{
216#define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
217	int needed_space = hdrsize;
218
219	if (key != NULL) {
220		/* XXX belongs in crypto code? */
221		needed_space += key->wk_cipher->ic_header;
222		/* XXX frags */
223	}
224	/*
225	 * We know we are called just before stripping an Ethernet
226	 * header and prepending an LLC header.  This means we know
227	 * there will be
228	 *	sizeof(struct ether_header) - sizeof(struct llc)
229	 * bytes recovered to which we need additional space for the
230	 * 802.11 header and any crypto header.
231	 */
232	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
233		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
234		if (n == NULL) {
235			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
236			    "%s: cannot expand storage\n", __func__);
237			ic->ic_stats.is_tx_nobuf++;
238			m_freem(m);
239			return NULL;
240		}
241		KASSERT(needed_space <= MHLEN,
242		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
243		/*
244		 * Setup new mbuf to have leading space to prepend the
245		 * 802.11 header and any crypto header bits that are
246		 * required (the latter are added when the driver calls
247		 * back to ieee80211_crypto_encap to do crypto encapsulation).
248		 */
249		/* NB: must be first 'cuz it clobbers m_data */
250		m_move_pkthdr(n, m);
251		n->m_len = 0;			/* NB: m_gethdr does not set */
252		n->m_data += needed_space;
253		/*
254		 * Pull up Ethernet header to create the expected layout.
255		 * We could use m_pullup but that's overkill (i.e. we don't
256		 * need the actual data) and it cannot fail so do it inline
257		 * for speed.
258		 */
259		/* NB: struct ether_header is known to be contiguous */
260		n->m_len += sizeof(struct ether_header);
261		m->m_len -= sizeof(struct ether_header);
262		m->m_data += sizeof(struct ether_header);
263		/*
264		 * Replace the head of the chain.
265		 */
266		n->m_next = m;
267		m = n;
268	}
269	return m;
270#undef TO_BE_RECLAIMED
271}
272
273/*
274 * Assign priority to a frame based on any vlan tag assigned
275 * to the station and/or any Diffserv setting in an IP header.
276 * Finally, if an ACM policy is setup (in station mode) it's
277 * applied.
278 */
279int
280ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
281{
282	int v_wme_ac, d_wme_ac, ac;
283#ifdef INET
284	struct ether_header *eh;
285#endif
286
287	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
288		ac = WME_AC_BE;
289		goto done;
290	}
291
292	/*
293	 * If node has a vlan tag then all traffic
294	 * to it must have a matching tag.
295	 */
296	v_wme_ac = 0;
297	if (ni->ni_vlan != 0) {
298		 struct m_tag *mtag = VLAN_OUTPUT_TAG(ic->ic_ifp, m);
299		 if (mtag != NULL) {
300			IEEE80211_NODE_STAT(ni, tx_novlantag);
301			return 1;
302		}
303		if (EVL_VLANOFTAG(VLAN_TAG_VALUE(mtag)) !=
304		    EVL_VLANOFTAG(ni->ni_vlan)) {
305			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
306			return 1;
307		}
308		/* map vlan priority to AC */
309		switch (EVL_PRIOFTAG(ni->ni_vlan)) {
310		case 1:
311		case 2:
312			v_wme_ac = WME_AC_BK;
313			break;
314		case 0:
315		case 3:
316			v_wme_ac = WME_AC_BE;
317			break;
318		case 4:
319		case 5:
320			v_wme_ac = WME_AC_VI;
321			break;
322		case 6:
323		case 7:
324			v_wme_ac = WME_AC_VO;
325			break;
326		}
327	}
328
329#ifdef INET
330	eh = mtod(m, struct ether_header *);
331	if (eh->ether_type == htons(ETHERTYPE_IP)) {
332		const struct ip *ip = (struct ip *)
333			(mtod(m, u_int8_t *) + sizeof (*eh));
334		/*
335		 * IP frame, map the TOS field.
336		 */
337		switch (ip->ip_tos) {
338		case 0x08:
339		case 0x20:
340			d_wme_ac = WME_AC_BK;	/* background */
341			break;
342		case 0x28:
343		case 0xa0:
344			d_wme_ac = WME_AC_VI;	/* video */
345			break;
346		case 0x30:			/* voice */
347		case 0xe0:
348		case 0x88:			/* XXX UPSD */
349		case 0xb8:
350			d_wme_ac = WME_AC_VO;
351			break;
352		default:
353			d_wme_ac = WME_AC_BE;
354			break;
355		}
356	} else {
357#endif /* INET */
358		d_wme_ac = WME_AC_BE;
359#ifdef INET
360	}
361#endif
362	/*
363	 * Use highest priority AC.
364	 */
365	if (v_wme_ac > d_wme_ac)
366		ac = v_wme_ac;
367	else
368		ac = d_wme_ac;
369
370	/*
371	 * Apply ACM policy.
372	 */
373	if (ic->ic_opmode == IEEE80211_M_STA) {
374		static const int acmap[4] = {
375			WME_AC_BK,	/* WME_AC_BE */
376			WME_AC_BK,	/* WME_AC_BK */
377			WME_AC_BE,	/* WME_AC_VI */
378			WME_AC_VI,	/* WME_AC_VO */
379		};
380		while (ac != WME_AC_BK &&
381		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
382			ac = acmap[ac];
383	}
384done:
385	M_WME_SETAC(m, ac);
386	return 0;
387}
388
389/*
390 * Return the transmit key to use in sending a frame to the specified
391 * destination. Multicast traffic always uses the group key which is
392 * installed the default tx key.  Otherwise if a unicast key is set
393 * we use that.  When no unicast key is set we fall back to the default
394 * transmit key unless WPA is enabled in which case there should be
395 * a unicast frame so we don't want to use a default key (which in
396 * this case is the group/multicast key).
397 */
398static __inline struct ieee80211_key *
399ieee80211_crypto_getkey(struct ieee80211com *ic,
400	const u_int8_t mac[IEEE80211_ADDR_LEN], struct ieee80211_node *ni)
401{
402#define	KEY_UNDEFINED(k)	((k).wk_cipher == &ieee80211_cipher_none)
403	if (IEEE80211_IS_MULTICAST(mac)) {
404		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
405		    KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
406			return NULL;
407		return &ic->ic_nw_keys[ic->ic_def_txkey];
408	} else if (KEY_UNDEFINED(ni->ni_ucastkey)) {
409		if ((ic->ic_flags & IEEE80211_F_WPA) ||
410		    ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
411		    KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
412			return NULL;
413		return &ic->ic_nw_keys[ic->ic_def_txkey];
414	} else {
415		return &ni->ni_ucastkey;
416	}
417#undef KEY_UNDEFINED
418}
419
420/*
421 * Encapsulate an outbound data frame.  The mbuf chain is updated.
422 * If an error is encountered NULL is returned.  The caller is required
423 * to provide a node reference and pullup the ethernet header in the
424 * first mbuf.
425 */
426struct mbuf *
427ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
428	struct ieee80211_node *ni)
429{
430	struct ether_header eh;
431	struct ieee80211_frame *wh;
432	struct ieee80211_key *key;
433	struct llc *llc;
434	int hdrsize, datalen;
435
436	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
437	memcpy(&eh, mtod(m, caddr_t), sizeof(struct ether_header));
438
439	/*
440	 * Insure space for additional headers.  First identify
441	 * transmit key to use in calculating any buffer adjustments
442	 * required.  This is also used below to do privacy
443	 * encapsulation work.  Then calculate the 802.11 header
444	 * size and any padding required by the driver.
445	 *
446	 * Note key may be NULL if we fall back to the default
447	 * transmit key and that is not set.  In that case the
448	 * buffer may not be expanded as needed by the cipher
449	 * routines, but they will/should discard it.
450	 */
451	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
452		key = ieee80211_crypto_getkey(ic, eh.ether_dhost, ni);
453		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
454			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
455			    "[%s] no default transmit key\n",
456			    ether_sprintf(ni->ni_macaddr));
457			/* XXX statistic */
458		}
459	} else
460		key = NULL;
461	/* XXX 4-address format */
462	if (ni->ni_flags & IEEE80211_NODE_QOS)
463		hdrsize = sizeof(struct ieee80211_qosframe);
464	else
465		hdrsize = sizeof(struct ieee80211_frame);
466	if (ic->ic_flags & IEEE80211_F_DATAPAD)
467		hdrsize = roundup(hdrsize, sizeof(u_int32_t));
468	m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
469	if (m == NULL) {
470		/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
471		goto bad;
472	}
473
474	/* NB: this could be optimized because of ieee80211_mbuf_adjust */
475	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
476	llc = mtod(m, struct llc *);
477	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
478	llc->llc_control = LLC_UI;
479	llc->llc_snap.org_code[0] = 0;
480	llc->llc_snap.org_code[1] = 0;
481	llc->llc_snap.org_code[2] = 0;
482	llc->llc_snap.ether_type = eh.ether_type;
483	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
484
485	M_PREPEND(m, hdrsize, M_DONTWAIT);
486	if (m == NULL) {
487		ic->ic_stats.is_tx_nobuf++;
488		goto bad;
489	}
490	wh = mtod(m, struct ieee80211_frame *);
491	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
492	*(u_int16_t *)wh->i_dur = 0;
493	switch (ic->ic_opmode) {
494	case IEEE80211_M_STA:
495		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
496		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
497		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
498		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
499		break;
500	case IEEE80211_M_IBSS:
501	case IEEE80211_M_AHDEMO:
502		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
503		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
504		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
505		IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
506		break;
507	case IEEE80211_M_HOSTAP:
508		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
509		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
510		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
511		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
512		break;
513	case IEEE80211_M_MONITOR:
514		goto bad;
515	}
516	if (eh.ether_type != htons(ETHERTYPE_PAE) ||
517	    (key != NULL && (ic->ic_flags & IEEE80211_F_WPA))) {
518		/*
519		 * IEEE 802.1X: send EAPOL frames always in the clear.
520		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
521		 */
522		if (key != NULL) {
523			wh->i_fc[1] |= IEEE80211_FC1_WEP;
524			/* XXX do fragmentation */
525			if (!ieee80211_crypto_enmic(ic, key, m)) {
526				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
527				    "[%s] enmic failed, discard frame\n",
528				    ether_sprintf(eh.ether_dhost));
529				/* XXX statistic */
530				goto bad;
531			}
532		}
533	}
534
535	if (ni->ni_flags & IEEE80211_NODE_QOS) {
536		struct ieee80211_qosframe *qwh =
537			(struct ieee80211_qosframe *) wh;
538		int ac, tid;
539
540		ac = M_WME_GETAC(m);
541		/* map from access class/queue to 11e header priorty value */
542		tid = WME_AC_TO_TID(ac);
543		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
544		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
545			qwh->i_qos[0] |= 1 << IEEE80211_QOS_ACKPOLICY_S;
546		qwh->i_qos[1] = 0;
547		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
548
549		*(u_int16_t *)wh->i_seq =
550		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
551		ni->ni_txseqs[tid]++;
552	} else {
553		*(u_int16_t *)wh->i_seq =
554		    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
555		ni->ni_txseqs[0]++;
556	}
557
558	IEEE80211_NODE_STAT(ni, tx_data);
559	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
560
561	return m;
562bad:
563	if (m != NULL)
564		m_freem(m);
565	return NULL;
566}
567
568/*
569 * Add a supported rates element id to a frame.
570 */
571static u_int8_t *
572ieee80211_add_rates(u_int8_t *frm, const struct ieee80211_rateset *rs)
573{
574	int nrates;
575
576	*frm++ = IEEE80211_ELEMID_RATES;
577	nrates = rs->rs_nrates;
578	if (nrates > IEEE80211_RATE_SIZE)
579		nrates = IEEE80211_RATE_SIZE;
580	*frm++ = nrates;
581	memcpy(frm, rs->rs_rates, nrates);
582	return frm + nrates;
583}
584
585/*
586 * Add an extended supported rates element id to a frame.
587 */
588static u_int8_t *
589ieee80211_add_xrates(u_int8_t *frm, const struct ieee80211_rateset *rs)
590{
591	/*
592	 * Add an extended supported rates element if operating in 11g mode.
593	 */
594	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
595		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
596		*frm++ = IEEE80211_ELEMID_XRATES;
597		*frm++ = nrates;
598		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
599		frm += nrates;
600	}
601	return frm;
602}
603
604/*
605 * Add an ssid elemet to a frame.
606 */
607static u_int8_t *
608ieee80211_add_ssid(u_int8_t *frm, const u_int8_t *ssid, u_int len)
609{
610	*frm++ = IEEE80211_ELEMID_SSID;
611	*frm++ = len;
612	memcpy(frm, ssid, len);
613	return frm + len;
614}
615
616/*
617 * Add an erp element to a frame.
618 */
619static u_int8_t *
620ieee80211_add_erp(u_int8_t *frm, struct ieee80211com *ic)
621{
622	u_int8_t erp;
623
624	*frm++ = IEEE80211_ELEMID_ERP;
625	*frm++ = 1;
626	erp = 0;
627	if (ic->ic_nonerpsta != 0)
628		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
629	if (ic->ic_flags & IEEE80211_F_USEPROT)
630		erp |= IEEE80211_ERP_USE_PROTECTION;
631	if (ic->ic_flags & IEEE80211_F_USEBARKER)
632		erp |= IEEE80211_ERP_LONG_PREAMBLE;
633	*frm++ = erp;
634	return frm;
635}
636
637static u_int8_t *
638ieee80211_setup_wpa_ie(struct ieee80211com *ic, u_int8_t *ie)
639{
640#define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
641#define	ADDSHORT(frm, v) do {			\
642	frm[0] = (v) & 0xff;			\
643	frm[1] = (v) >> 8;			\
644	frm += 2;				\
645} while (0)
646#define	ADDSELECTOR(frm, sel) do {		\
647	memcpy(frm, sel, 4);			\
648	frm += 4;				\
649} while (0)
650	static const u_int8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
651	static const u_int8_t cipher_suite[][4] = {
652		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
653		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
654		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
655		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
656		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
657		{ WPA_OUI_BYTES, WPA_CSE_NULL },
658	};
659	static const u_int8_t wep104_suite[4] =
660		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
661	static const u_int8_t key_mgt_unspec[4] =
662		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
663	static const u_int8_t key_mgt_psk[4] =
664		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
665	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
666	u_int8_t *frm = ie;
667	u_int8_t *selcnt;
668
669	*frm++ = IEEE80211_ELEMID_VENDOR;
670	*frm++ = 0;				/* length filled in below */
671	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
672	frm += sizeof(oui);
673	ADDSHORT(frm, WPA_VERSION);
674
675	/* XXX filter out CKIP */
676
677	/* multicast cipher */
678	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
679	    rsn->rsn_mcastkeylen >= 13)
680		ADDSELECTOR(frm, wep104_suite);
681	else
682		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
683
684	/* unicast cipher list */
685	selcnt = frm;
686	ADDSHORT(frm, 0);			/* selector count */
687	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
688		selcnt[0]++;
689		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
690	}
691	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
692		selcnt[0]++;
693		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
694	}
695
696	/* authenticator selector list */
697	selcnt = frm;
698	ADDSHORT(frm, 0);			/* selector count */
699	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
700		selcnt[0]++;
701		ADDSELECTOR(frm, key_mgt_unspec);
702	}
703	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
704		selcnt[0]++;
705		ADDSELECTOR(frm, key_mgt_psk);
706	}
707
708	/* optional capabilities */
709	if (rsn->rsn_caps != 0)
710		ADDSHORT(frm, rsn->rsn_caps);
711
712	/* calculate element length */
713	ie[1] = frm - ie - 2;
714	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
715		("WPA IE too big, %u > %zu",
716		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
717	return frm;
718#undef ADDSHORT
719#undef ADDSELECTOR
720#undef WPA_OUI_BYTES
721}
722
723static u_int8_t *
724ieee80211_setup_rsn_ie(struct ieee80211com *ic, u_int8_t *ie)
725{
726#define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
727#define	ADDSHORT(frm, v) do {			\
728	frm[0] = (v) & 0xff;			\
729	frm[1] = (v) >> 8;			\
730	frm += 2;				\
731} while (0)
732#define	ADDSELECTOR(frm, sel) do {		\
733	memcpy(frm, sel, 4);			\
734	frm += 4;				\
735} while (0)
736	static const u_int8_t cipher_suite[][4] = {
737		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
738		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
739		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
740		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
741		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
742		{ RSN_OUI_BYTES, RSN_CSE_NULL },
743	};
744	static const u_int8_t wep104_suite[4] =
745		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
746	static const u_int8_t key_mgt_unspec[4] =
747		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
748	static const u_int8_t key_mgt_psk[4] =
749		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
750	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
751	u_int8_t *frm = ie;
752	u_int8_t *selcnt;
753
754	*frm++ = IEEE80211_ELEMID_RSN;
755	*frm++ = 0;				/* length filled in below */
756	ADDSHORT(frm, RSN_VERSION);
757
758	/* XXX filter out CKIP */
759
760	/* multicast cipher */
761	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
762	    rsn->rsn_mcastkeylen >= 13)
763		ADDSELECTOR(frm, wep104_suite);
764	else
765		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
766
767	/* unicast cipher list */
768	selcnt = frm;
769	ADDSHORT(frm, 0);			/* selector count */
770	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
771		selcnt[0]++;
772		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
773	}
774	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
775		selcnt[0]++;
776		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
777	}
778
779	/* authenticator selector list */
780	selcnt = frm;
781	ADDSHORT(frm, 0);			/* selector count */
782	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
783		selcnt[0]++;
784		ADDSELECTOR(frm, key_mgt_unspec);
785	}
786	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
787		selcnt[0]++;
788		ADDSELECTOR(frm, key_mgt_psk);
789	}
790
791	/* optional capabilities */
792	if (rsn->rsn_caps != 0)
793		ADDSHORT(frm, rsn->rsn_caps);
794	/* XXX PMKID */
795
796	/* calculate element length */
797	ie[1] = frm - ie - 2;
798	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
799		("RSN IE too big, %u > %zu",
800		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
801	return frm;
802#undef ADDSELECTOR
803#undef ADDSHORT
804#undef RSN_OUI_BYTES
805}
806
807/*
808 * Add a WPA/RSN element to a frame.
809 */
810static u_int8_t *
811ieee80211_add_wpa(u_int8_t *frm, struct ieee80211com *ic)
812{
813
814	KASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
815	if (ic->ic_flags & IEEE80211_F_WPA2)
816		frm = ieee80211_setup_rsn_ie(ic, frm);
817	if (ic->ic_flags & IEEE80211_F_WPA1)
818		frm = ieee80211_setup_wpa_ie(ic, frm);
819	return frm;
820}
821
822#define	WME_OUI_BYTES		0x00, 0x50, 0xf2
823/*
824 * Add a WME information element to a frame.
825 */
826static u_int8_t *
827ieee80211_add_wme_info(u_int8_t *frm, struct ieee80211_wme_state *wme)
828{
829	static const struct ieee80211_wme_info info = {
830		.wme_id		= IEEE80211_ELEMID_VENDOR,
831		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
832		.wme_oui	= { WME_OUI_BYTES },
833		.wme_type	= WME_OUI_TYPE,
834		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
835		.wme_version	= WME_VERSION,
836		.wme_info	= 0,
837	};
838	memcpy(frm, &info, sizeof(info));
839	return frm + sizeof(info);
840}
841
842/*
843 * Add a WME parameters element to a frame.
844 */
845static u_int8_t *
846ieee80211_add_wme_param(u_int8_t *frm, struct ieee80211_wme_state *wme)
847{
848#define	SM(_v, _f)	(((_v) << _f##_S) & _f)
849#define	ADDSHORT(frm, v) do {			\
850	frm[0] = (v) & 0xff;			\
851	frm[1] = (v) >> 8;			\
852	frm += 2;				\
853} while (0)
854	/* NB: this works 'cuz a param has an info at the front */
855	static const struct ieee80211_wme_info param = {
856		.wme_id		= IEEE80211_ELEMID_VENDOR,
857		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
858		.wme_oui	= { WME_OUI_BYTES },
859		.wme_type	= WME_OUI_TYPE,
860		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
861		.wme_version	= WME_VERSION,
862	};
863	int i;
864
865	memcpy(frm, &param, sizeof(param));
866	frm += __offsetof(struct ieee80211_wme_info, wme_info);
867	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
868	*frm++ = 0;					/* reserved field */
869	for (i = 0; i < WME_NUM_AC; i++) {
870		const struct wmeParams *ac =
871		       &wme->wme_bssChanParams.cap_wmeParams[i];
872		*frm++ = SM(i, WME_PARAM_ACI)
873		       | SM(ac->wmep_acm, WME_PARAM_ACM)
874		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
875		       ;
876		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
877		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
878		       ;
879		ADDSHORT(frm, ac->wmep_txopLimit);
880	}
881	return frm;
882#undef SM
883#undef ADDSHORT
884}
885#undef WME_OUI_BYTES
886
887/*
888 * Send a management frame.  The node is for the destination (or ic_bss
889 * when in station mode).  Nodes other than ic_bss have their reference
890 * count bumped to reflect our use for an indeterminant time.
891 */
892int
893ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
894	int type, int arg)
895{
896#define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
897	struct mbuf *m;
898	u_int8_t *frm;
899	enum ieee80211_phymode mode;
900	u_int16_t capinfo;
901	int has_challenge, is_shared_key, ret, timer, status;
902
903	KASSERT(ni != NULL, ("null node"));
904
905	/*
906	 * Hold a reference on the node so it doesn't go away until after
907	 * the xmit is complete all the way in the driver.  On error we
908	 * will remove our reference.
909	 */
910	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
911		"ieee80211_ref_node (%s:%u) %s refcnt %d\n",
912		__func__, __LINE__,
913		 ether_sprintf(ni->ni_macaddr),
914		 ieee80211_node_refcnt(ni)+1);
915	ieee80211_ref_node(ni);
916
917	timer = 0;
918	switch (type) {
919	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
920		/*
921		 * prreq frame format
922		 *	[tlv] ssid
923		 *	[tlv] supported rates
924		 *	[tlv] extended supported rates
925		 *	[tlv] WME (optional)
926		 *	[tlv] user-specified ie's
927		 */
928		m = ieee80211_getmgtframe(&frm,
929			 2 + IEEE80211_NWID_LEN
930		       + 2 + IEEE80211_RATE_SIZE
931		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
932		       + sizeof(struct ieee80211_wme_param)
933		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
934		);
935		if (m == NULL)
936			senderr(ENOMEM, is_tx_nobuf);
937
938		frm = ieee80211_add_ssid(frm, ic->ic_des_essid, ic->ic_des_esslen);
939		mode = ieee80211_chan2mode(ic, ni->ni_chan);
940		frm = ieee80211_add_rates(frm, &ic->ic_sup_rates[mode]);
941		frm = ieee80211_add_xrates(frm, &ic->ic_sup_rates[mode]);
942		if (ic->ic_flags & IEEE80211_F_WME)
943			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
944		if (ic->ic_opt_ie != NULL) {
945			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
946			frm += ic->ic_opt_ie_len;
947		}
948		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
949
950		IEEE80211_NODE_STAT(ni, tx_probereq);
951		if (ic->ic_opmode == IEEE80211_M_STA)
952			timer = IEEE80211_TRANS_WAIT;
953		break;
954
955	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
956		/*
957		 * probe response frame format
958		 *	[8] time stamp
959		 *	[2] beacon interval
960		 *	[2] cabability information
961		 *	[tlv] ssid
962		 *	[tlv] supported rates
963		 *	[tlv] parameter set (FH/DS)
964		 *	[tlv] parameter set (IBSS)
965		 *	[tlv] extended rate phy (ERP)
966		 *	[tlv] extended supported rates
967		 *	[tlv] WPA
968		 */
969		m = ieee80211_getmgtframe(&frm,
970			 8
971		       + sizeof(u_int16_t)
972		       + sizeof(u_int16_t)
973		       + 2 + IEEE80211_NWID_LEN
974		       + 2 + IEEE80211_RATE_SIZE
975		       + 7	/* max(7,3) */
976		       + 6
977		       + 3
978		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
979		       /* XXX !WPA1+WPA2 fits w/o a cluster */
980		       + (ic->ic_flags & IEEE80211_F_WPA ?
981				2*sizeof(struct ieee80211_ie_wpa) : 0)
982		);
983		if (m == NULL)
984			senderr(ENOMEM, is_tx_nobuf);
985
986		memset(frm, 0, 8);	/* timestamp should be filled later */
987		frm += 8;
988		*(u_int16_t *)frm = htole16(ic->ic_bss->ni_intval);
989		frm += 2;
990		if (ic->ic_opmode == IEEE80211_M_IBSS)
991			capinfo = IEEE80211_CAPINFO_IBSS;
992		else
993			capinfo = IEEE80211_CAPINFO_ESS;
994		if (ic->ic_flags & IEEE80211_F_PRIVACY)
995			capinfo |= IEEE80211_CAPINFO_PRIVACY;
996		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
997		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
998			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
999		if (ic->ic_flags & IEEE80211_F_SHSLOT)
1000			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1001		*(u_int16_t *)frm = htole16(capinfo);
1002		frm += 2;
1003
1004		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
1005				ic->ic_bss->ni_esslen);
1006		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1007
1008		if (ic->ic_phytype == IEEE80211_T_FH) {
1009                        *frm++ = IEEE80211_ELEMID_FHPARMS;
1010                        *frm++ = 5;
1011                        *frm++ = ni->ni_fhdwell & 0x00ff;
1012                        *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1013                        *frm++ = IEEE80211_FH_CHANSET(
1014			    ieee80211_chan2ieee(ic, ni->ni_chan));
1015                        *frm++ = IEEE80211_FH_CHANPAT(
1016			    ieee80211_chan2ieee(ic, ni->ni_chan));
1017                        *frm++ = ni->ni_fhindex;
1018		} else {
1019			*frm++ = IEEE80211_ELEMID_DSPARMS;
1020			*frm++ = 1;
1021			*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1022		}
1023
1024		if (ic->ic_opmode == IEEE80211_M_IBSS) {
1025			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1026			*frm++ = 2;
1027			*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1028		}
1029		if (ic->ic_flags & IEEE80211_F_WPA)
1030			frm = ieee80211_add_wpa(frm, ic);
1031		if (ic->ic_curmode == IEEE80211_MODE_11G)
1032			frm = ieee80211_add_erp(frm, ic);
1033		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1034		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1035		break;
1036
1037	case IEEE80211_FC0_SUBTYPE_AUTH:
1038		status = arg >> 16;
1039		arg &= 0xffff;
1040		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1041		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1042		    ni->ni_challenge != NULL);
1043
1044		/*
1045		 * Deduce whether we're doing open authentication or
1046		 * shared key authentication.  We do the latter if
1047		 * we're in the middle of a shared key authentication
1048		 * handshake or if we're initiating an authentication
1049		 * request and configured to use shared key.
1050		 */
1051		is_shared_key = has_challenge ||
1052		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1053		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1054		      ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1055
1056		m = ieee80211_getmgtframe(&frm,
1057			  3 * sizeof(u_int16_t)
1058			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1059				sizeof(u_int16_t)+IEEE80211_CHALLENGE_LEN : 0)
1060		);
1061		if (m == NULL)
1062			senderr(ENOMEM, is_tx_nobuf);
1063
1064		((u_int16_t *)frm)[0] =
1065		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1066		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1067		((u_int16_t *)frm)[1] = htole16(arg);	/* sequence number */
1068		((u_int16_t *)frm)[2] = htole16(status);/* status */
1069
1070		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1071			((u_int16_t *)frm)[3] =
1072			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1073			    IEEE80211_ELEMID_CHALLENGE);
1074			memcpy(&((u_int16_t *)frm)[4], ni->ni_challenge,
1075			    IEEE80211_CHALLENGE_LEN);
1076			m->m_pkthdr.len = m->m_len =
1077				4 * sizeof(u_int16_t) + IEEE80211_CHALLENGE_LEN;
1078			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1079				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1080				    "[%s] request encrypt frame (%s)\n",
1081				    ether_sprintf(ni->ni_macaddr), __func__);
1082				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1083			}
1084		} else
1085			m->m_pkthdr.len = m->m_len = 3 * sizeof(u_int16_t);
1086
1087		/* XXX not right for shared key */
1088		if (status == IEEE80211_STATUS_SUCCESS)
1089			IEEE80211_NODE_STAT(ni, tx_auth);
1090		else
1091			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1092
1093		/*
1094		 * When 802.1x is not in use mark the port
1095		 * authorized at this point so traffic can flow.
1096		 */
1097		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1098		    status == IEEE80211_STATUS_SUCCESS &&
1099		    ni->ni_authmode != IEEE80211_AUTH_8021X)
1100			ieee80211_node_authorize(ic, ni);
1101		if (ic->ic_opmode == IEEE80211_M_STA)
1102			timer = IEEE80211_TRANS_WAIT;
1103		break;
1104
1105	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1106		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1107			"[%s] send station deauthenticate (reason %d)\n",
1108			ether_sprintf(ni->ni_macaddr), arg);
1109		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1110		if (m == NULL)
1111			senderr(ENOMEM, is_tx_nobuf);
1112		*(u_int16_t *)frm = htole16(arg);	/* reason */
1113		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1114
1115		IEEE80211_NODE_STAT(ni, tx_deauth);
1116		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1117
1118		ieee80211_node_unauthorize(ic, ni);	/* port closed */
1119		break;
1120
1121	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1122	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1123		/*
1124		 * asreq frame format
1125		 *	[2] capability information
1126		 *	[2] listen interval
1127		 *	[6*] current AP address (reassoc only)
1128		 *	[tlv] ssid
1129		 *	[tlv] supported rates
1130		 *	[tlv] extended supported rates
1131		 *	[tlv] WME
1132		 *	[tlv] user-specified ie's
1133		 */
1134		m = ieee80211_getmgtframe(&frm,
1135			 sizeof(u_int16_t)
1136		       + sizeof(u_int16_t)
1137		       + IEEE80211_ADDR_LEN
1138		       + 2 + IEEE80211_NWID_LEN
1139		       + 2 + IEEE80211_RATE_SIZE
1140		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1141		       + sizeof(struct ieee80211_wme_info)
1142		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1143		);
1144		if (m == NULL)
1145			senderr(ENOMEM, is_tx_nobuf);
1146
1147		capinfo = 0;
1148		if (ic->ic_opmode == IEEE80211_M_IBSS)
1149			capinfo |= IEEE80211_CAPINFO_IBSS;
1150		else		/* IEEE80211_M_STA */
1151			capinfo |= IEEE80211_CAPINFO_ESS;
1152		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1153			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1154		/*
1155		 * NB: Some 11a AP's reject the request when
1156		 *     short premable is set.
1157		 */
1158		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1159		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1160			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1161		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) &&
1162		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1163			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1164		*(u_int16_t *)frm = htole16(capinfo);
1165		frm += 2;
1166
1167		*(u_int16_t *)frm = htole16(ic->ic_lintval);
1168		frm += 2;
1169
1170		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1171			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1172			frm += IEEE80211_ADDR_LEN;
1173		}
1174
1175		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1176		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1177		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1178		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1179			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1180		if (ic->ic_opt_ie != NULL) {
1181			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1182			frm += ic->ic_opt_ie_len;
1183		}
1184		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1185
1186		timer = IEEE80211_TRANS_WAIT;
1187		break;
1188
1189	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1190	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1191		/*
1192		 * asreq frame format
1193		 *	[2] capability information
1194		 *	[2] status
1195		 *	[2] association ID
1196		 *	[tlv] supported rates
1197		 *	[tlv] extended supported rates
1198		 *	[tlv] WME (if enabled and STA enabled)
1199		 */
1200		m = ieee80211_getmgtframe(&frm,
1201			 sizeof(u_int16_t)
1202		       + sizeof(u_int16_t)
1203		       + sizeof(u_int16_t)
1204		       + 2 + IEEE80211_RATE_SIZE
1205		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1206		       + sizeof(struct ieee80211_wme_param)
1207		);
1208		if (m == NULL)
1209			senderr(ENOMEM, is_tx_nobuf);
1210
1211		capinfo = IEEE80211_CAPINFO_ESS;
1212		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1213			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1214		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1215		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1216			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1217		if (ic->ic_flags & IEEE80211_F_SHSLOT)
1218			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1219		*(u_int16_t *)frm = htole16(capinfo);
1220		frm += 2;
1221
1222		*(u_int16_t *)frm = htole16(arg);	/* status */
1223		frm += 2;
1224
1225		if (arg == IEEE80211_STATUS_SUCCESS) {
1226			*(u_int16_t *)frm = htole16(ni->ni_associd);
1227			IEEE80211_NODE_STAT(ni, tx_assoc);
1228		} else
1229			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1230		frm += 2;
1231
1232		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1233		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1234		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1235			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1236		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1237		break;
1238
1239	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1240		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1241			"[%s] send station disassociate (reason %d)\n",
1242			ether_sprintf(ni->ni_macaddr), arg);
1243		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1244		if (m == NULL)
1245			senderr(ENOMEM, is_tx_nobuf);
1246		*(u_int16_t *)frm = htole16(arg);	/* reason */
1247		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1248
1249		IEEE80211_NODE_STAT(ni, tx_disassoc);
1250		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1251		break;
1252
1253	default:
1254		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1255			"[%s] invalid mgmt frame type %u\n",
1256			ether_sprintf(ni->ni_macaddr), type);
1257		senderr(EINVAL, is_tx_unknownmgt);
1258		/* NOTREACHED */
1259	}
1260
1261	ret = ieee80211_mgmt_output(ic, ni, m, type);
1262	if (ret == 0) {
1263		if (timer)
1264			ic->ic_mgt_timer = timer;
1265	} else {
1266bad:
1267		ieee80211_free_node(ni);
1268	}
1269	return ret;
1270#undef senderr
1271}
1272
1273/*
1274 * Allocate a beacon frame and fillin the appropriate bits.
1275 */
1276struct mbuf *
1277ieee80211_beacon_alloc(struct ieee80211com *ic, struct ieee80211_node *ni,
1278	struct ieee80211_beacon_offsets *bo)
1279{
1280	struct ifnet *ifp = ic->ic_ifp;
1281	struct ieee80211_frame *wh;
1282	struct mbuf *m;
1283	int pktlen;
1284	u_int8_t *frm, *efrm;
1285	u_int16_t capinfo;
1286	struct ieee80211_rateset *rs;
1287
1288	/*
1289	 * beacon frame format
1290	 *	[8] time stamp
1291	 *	[2] beacon interval
1292	 *	[2] cabability information
1293	 *	[tlv] ssid
1294	 *	[tlv] supported rates
1295	 *	[3] parameter set (DS)
1296	 *	[tlv] parameter set (IBSS/TIM)
1297	 *	[tlv] extended rate phy (ERP)
1298	 *	[tlv] extended supported rates
1299	 *	[tlv] WME parameters
1300	 *	[tlv] WPA/RSN parameters
1301	 * XXX Vendor-specific OIDs (e.g. Atheros)
1302	 * NB: we allocate the max space required for the TIM bitmap.
1303	 */
1304	rs = &ni->ni_rates;
1305	pktlen =   8					/* time stamp */
1306		 + sizeof(u_int16_t)			/* beacon interval */
1307		 + sizeof(u_int16_t)			/* capabilities */
1308		 + 2 + ni->ni_esslen			/* ssid */
1309	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
1310	         + 2 + 1				/* DS parameters */
1311		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
1312		 + 2 + 1				/* ERP */
1313	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1314		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
1315			sizeof(struct ieee80211_wme_param) : 0)
1316		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
1317			2*sizeof(struct ieee80211_ie_wpa) : 0)
1318		 ;
1319	m = ieee80211_getmgtframe(&frm, pktlen);
1320	if (m == NULL) {
1321		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1322			"%s: cannot get buf; size %u\n", __func__, pktlen);
1323		ic->ic_stats.is_tx_nobuf++;
1324		return NULL;
1325	}
1326
1327	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
1328	frm += 8;
1329	*(u_int16_t *)frm = htole16(ni->ni_intval);
1330	frm += 2;
1331	if (ic->ic_opmode == IEEE80211_M_IBSS)
1332		capinfo = IEEE80211_CAPINFO_IBSS;
1333	else
1334		capinfo = IEEE80211_CAPINFO_ESS;
1335	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1336		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1337	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1338	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1339		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1340	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1341		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1342	bo->bo_caps = (u_int16_t *)frm;
1343	*(u_int16_t *)frm = htole16(capinfo);
1344	frm += 2;
1345	*frm++ = IEEE80211_ELEMID_SSID;
1346	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
1347		*frm++ = ni->ni_esslen;
1348		memcpy(frm, ni->ni_essid, ni->ni_esslen);
1349		frm += ni->ni_esslen;
1350	} else
1351		*frm++ = 0;
1352	frm = ieee80211_add_rates(frm, rs);
1353	if (ic->ic_curmode != IEEE80211_MODE_FH) {
1354		*frm++ = IEEE80211_ELEMID_DSPARMS;
1355		*frm++ = 1;
1356		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1357	}
1358	bo->bo_tim = frm;
1359	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1360		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1361		*frm++ = 2;
1362		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1363		bo->bo_tim_len = 0;
1364	} else {
1365		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
1366
1367		tie->tim_ie = IEEE80211_ELEMID_TIM;
1368		tie->tim_len = 4;	/* length */
1369		tie->tim_count = 0;	/* DTIM count */
1370		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
1371		tie->tim_bitctl = 0;	/* bitmap control */
1372		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
1373		frm += sizeof(struct ieee80211_tim_ie);
1374		bo->bo_tim_len = 1;
1375	}
1376	bo->bo_trailer = frm;
1377	if (ic->ic_flags & IEEE80211_F_WME) {
1378		bo->bo_wme = frm;
1379		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1380	}
1381	if (ic->ic_flags & IEEE80211_F_WPA)
1382		frm = ieee80211_add_wpa(frm, ic);
1383	if (ic->ic_curmode == IEEE80211_MODE_11G)
1384		frm = ieee80211_add_erp(frm, ic);
1385	efrm = ieee80211_add_xrates(frm, rs);
1386	bo->bo_trailer_len = efrm - bo->bo_trailer;
1387	m->m_pkthdr.len = m->m_len = efrm - mtod(m, u_int8_t *);
1388
1389	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1390	KASSERT(m != NULL, ("no space for 802.11 header?"));
1391	wh = mtod(m, struct ieee80211_frame *);
1392	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1393	    IEEE80211_FC0_SUBTYPE_BEACON;
1394	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1395	*(u_int16_t *)wh->i_dur = 0;
1396	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
1397	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
1398	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
1399	*(u_int16_t *)wh->i_seq = 0;
1400
1401	return m;
1402}
1403
1404/*
1405 * Update the dynamic parts of a beacon frame based on the current state.
1406 */
1407int
1408ieee80211_beacon_update(struct ieee80211com *ic, struct ieee80211_node *ni,
1409	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
1410{
1411	int len_changed = 0;
1412	u_int16_t capinfo;
1413
1414	IEEE80211_BEACON_LOCK(ic);
1415	/* XXX faster to recalculate entirely or just changes? */
1416	if (ic->ic_opmode == IEEE80211_M_IBSS)
1417		capinfo = IEEE80211_CAPINFO_IBSS;
1418	else
1419		capinfo = IEEE80211_CAPINFO_ESS;
1420	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1421		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1422	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1423	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1424		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1425	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1426		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1427	*bo->bo_caps = htole16(capinfo);
1428
1429	if (ic->ic_flags & IEEE80211_F_WME) {
1430		struct ieee80211_wme_state *wme = &ic->ic_wme;
1431
1432		/*
1433		 * Check for agressive mode change.  When there is
1434		 * significant high priority traffic in the BSS
1435		 * throttle back BE traffic by using conservative
1436		 * parameters.  Otherwise BE uses agressive params
1437		 * to optimize performance of legacy/non-QoS traffic.
1438		 */
1439		if (wme->wme_flags & WME_F_AGGRMODE) {
1440			if (wme->wme_hipri_traffic >
1441			    wme->wme_hipri_switch_thresh) {
1442				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1443				    "%s: traffic %u, disable aggressive mode\n",
1444				    __func__, wme->wme_hipri_traffic);
1445				wme->wme_flags &= ~WME_F_AGGRMODE;
1446				ieee80211_wme_updateparams_locked(ic);
1447				wme->wme_hipri_traffic =
1448					wme->wme_hipri_switch_hysteresis;
1449			} else
1450				wme->wme_hipri_traffic = 0;
1451		} else {
1452			if (wme->wme_hipri_traffic <=
1453			    wme->wme_hipri_switch_thresh) {
1454				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1455				    "%s: traffic %u, enable aggressive mode\n",
1456				    __func__, wme->wme_hipri_traffic);
1457				wme->wme_flags |= WME_F_AGGRMODE;
1458				ieee80211_wme_updateparams_locked(ic);
1459				wme->wme_hipri_traffic = 0;
1460			} else
1461				wme->wme_hipri_traffic =
1462					wme->wme_hipri_switch_hysteresis;
1463		}
1464		if (ic->ic_flags & IEEE80211_F_WMEUPDATE) {
1465			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
1466			ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1467		}
1468	}
1469
1470	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
1471		struct ieee80211_tim_ie *tie =
1472			(struct ieee80211_tim_ie *) bo->bo_tim;
1473		if (ic->ic_flags & IEEE80211_F_TIMUPDATE) {
1474			u_int timlen, timoff, i;
1475			/*
1476			 * ATIM/DTIM needs updating.  If it fits in the
1477			 * current space allocated then just copy in the
1478			 * new bits.  Otherwise we need to move any trailing
1479			 * data to make room.  Note that we know there is
1480			 * contiguous space because ieee80211_beacon_allocate
1481			 * insures there is space in the mbuf to write a
1482			 * maximal-size virtual bitmap (based on ic_max_aid).
1483			 */
1484			/*
1485			 * Calculate the bitmap size and offset, copy any
1486			 * trailer out of the way, and then copy in the
1487			 * new bitmap and update the information element.
1488			 * Note that the tim bitmap must contain at least
1489			 * one byte and any offset must be even.
1490			 */
1491			if (ic->ic_ps_pending != 0) {
1492				timoff = 128;		/* impossibly large */
1493				for (i = 0; i < ic->ic_tim_len; i++)
1494					if (ic->ic_tim_bitmap[i]) {
1495						timoff = i &~ 1;
1496						break;
1497					}
1498				KASSERT(timoff != 128, ("tim bitmap empty!"));
1499				for (i = ic->ic_tim_len-1; i >= timoff; i--)
1500					if (ic->ic_tim_bitmap[i])
1501						break;
1502				timlen = 1 + (i - timoff);
1503			} else {
1504				timoff = 0;
1505				timlen = 1;
1506			}
1507			if (timlen != bo->bo_tim_len) {
1508				/* copy up/down trailer */
1509				ovbcopy(bo->bo_trailer, tie->tim_bitmap+timlen,
1510					bo->bo_trailer_len);
1511				bo->bo_trailer = tie->tim_bitmap+timlen;
1512				bo->bo_wme = bo->bo_trailer;
1513				bo->bo_tim_len = timlen;
1514
1515				/* update information element */
1516				tie->tim_len = 3 + timlen;
1517				tie->tim_bitctl = timoff;
1518				len_changed = 1;
1519			}
1520			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
1521				bo->bo_tim_len);
1522
1523			ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
1524
1525			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1526				"%s: TIM updated, pending %u, off %u, len %u\n",
1527				__func__, ic->ic_ps_pending, timoff, timlen);
1528		}
1529		/* count down DTIM period */
1530		if (tie->tim_count == 0)
1531			tie->tim_count = tie->tim_period - 1;
1532		else
1533			tie->tim_count--;
1534		/* update state for buffered multicast frames on DTIM */
1535		if (mcast && (tie->tim_count == 1 || tie->tim_period == 1))
1536			tie->tim_bitctl |= 1;
1537		else
1538			tie->tim_bitctl &= ~1;
1539	}
1540	IEEE80211_BEACON_UNLOCK(ic);
1541
1542	return len_changed;
1543}
1544
1545/*
1546 * Save an outbound packet for a node in power-save sleep state.
1547 * The new packet is placed on the node's saved queue, and the TIM
1548 * is changed, if necessary.
1549 */
1550void
1551ieee80211_pwrsave(struct ieee80211com *ic, struct ieee80211_node *ni,
1552		  struct mbuf *m)
1553{
1554	int qlen, age;
1555
1556	IEEE80211_NODE_SAVEQ_LOCK(ni);
1557	if (_IF_QFULL(&ni->ni_savedq)) {
1558		_IF_DROP(&ni->ni_savedq);
1559		IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1560		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1561			"[%s] pwr save q overflow, drops %d (size %d)\n",
1562			ether_sprintf(ni->ni_macaddr),
1563			ni->ni_savedq.ifq_drops, IEEE80211_PS_MAX_QUEUE);
1564#ifdef IEEE80211_DEBUG
1565		if (ieee80211_msg_dumppkts(ic))
1566			ieee80211_dump_pkt(mtod(m, caddr_t), m->m_len, -1, -1);
1567#endif
1568		m_freem(m);
1569		return;
1570	}
1571	/*
1572	 * Tag the frame with it's expiry time and insert
1573	 * it in the queue.  The aging interval is 4 times
1574	 * the listen interval specified by the station.
1575	 * Frames that sit around too long are reclaimed
1576	 * using this information.
1577	 */
1578	/* XXX handle overflow? */
1579	age = ((ni->ni_intval * ic->ic_lintval) << 2) / 1024; /* TU -> secs */
1580	_IEEE80211_NODE_SAVEQ_ENQUEUE(ni, m, qlen, age);
1581	IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1582
1583	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1584		"[%s] save frame, %u now queued\n",
1585		ether_sprintf(ni->ni_macaddr), qlen);
1586
1587	if (qlen == 1)
1588		ic->ic_set_tim(ic, ni, 1);
1589}
1590