xref: /netbsd-src/sys/net80211/ieee80211_output.c (revision 481d3881954fd794ca5f2d880b68c53a5db8620e)
1 /*	$NetBSD: ieee80211_output.c,v 1.68 2024/07/05 04:31:53 rin Exp $	*/
2 
3 /*
4  * Copyright (c) 2001 Atsushi Onoe
5  * Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * Alternatively, this software may be distributed under the terms of the
20  * GNU General Public License ("GPL") version 2 as published by the Free
21  * Software Foundation.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifdef __FreeBSD__
37 __FBSDID("$FreeBSD: src/sys/net80211/ieee80211_output.c,v 1.34 2005/08/10 16:22:29 sam Exp $");
38 #endif
39 #ifdef __NetBSD__
40 __KERNEL_RCSID(0, "$NetBSD: ieee80211_output.c,v 1.68 2024/07/05 04:31:53 rin Exp $");
41 #endif
42 
43 #ifdef _KERNEL_OPT
44 #include "opt_inet.h"
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/mbuf.h>
50 #include <sys/kernel.h>
51 #include <sys/endian.h>
52 #include <sys/errno.h>
53 #include <sys/proc.h>
54 #include <sys/sysctl.h>
55 
56 #include <net/if.h>
57 #include <net/if_llc.h>
58 #include <net/if_media.h>
59 #include <net/if_arp.h>
60 #include <net/if_ether.h>
61 #include <net/if_llc.h>
62 #include <net/if_vlanvar.h>
63 
64 #include <net80211/ieee80211_netbsd.h>
65 #include <net80211/ieee80211_var.h>
66 
67 #include <net/bpf.h>
68 
69 #ifdef INET
70 #include <netinet/in.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/in_var.h>
73 #include <netinet/ip.h>
74 #include <net/if_ether.h>
75 #endif
76 
77 static int ieee80211_fragment(struct ieee80211com *, struct mbuf *,
78 	u_int hdrsize, u_int ciphdrsize, u_int mtu);
79 
80 #ifdef IEEE80211_DEBUG
81 /*
82  * Decide if an outbound management frame should be
83  * printed when debugging is enabled.  This filters some
84  * of the less interesting frames that come frequently
85  * (e.g. beacons).
86  */
87 static __inline int
doprint(struct ieee80211com * ic,int subtype)88 doprint(struct ieee80211com *ic, int subtype)
89 {
90 	switch (subtype) {
91 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
92 		return (ic->ic_opmode == IEEE80211_M_IBSS);
93 	}
94 	return 1;
95 }
96 #endif
97 
98 /*
99  * Set the direction field and address fields of an outgoing
100  * non-QoS frame.  Note this should be called early on in
101  * constructing a frame as it sets i_fc[1]; other bits can
102  * then be or'd in.
103  */
104 static void
ieee80211_send_setup(struct ieee80211com * ic,struct ieee80211_node * ni,struct ieee80211_frame * wh,int type,const u_int8_t sa[IEEE80211_ADDR_LEN],const u_int8_t da[IEEE80211_ADDR_LEN],const u_int8_t bssid[IEEE80211_ADDR_LEN])105 ieee80211_send_setup(struct ieee80211com *ic,
106 	struct ieee80211_node *ni,
107 	struct ieee80211_frame *wh,
108 	int type,
109 	const u_int8_t sa[IEEE80211_ADDR_LEN],
110 	const u_int8_t da[IEEE80211_ADDR_LEN],
111 	const u_int8_t bssid[IEEE80211_ADDR_LEN])
112 {
113 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
114 
115 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
116 
117 	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
118 		switch (ic->ic_opmode) {
119 		case IEEE80211_M_STA:
120 			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
121 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
122 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
123 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
124 			break;
125 
126 		case IEEE80211_M_IBSS:
127 		case IEEE80211_M_AHDEMO:
128 			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
129 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
130 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
131 			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
132 			break;
133 
134 		case IEEE80211_M_HOSTAP:
135 			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
136 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
137 			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
138 			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
139 			break;
140 
141 		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
142 			break;
143 		}
144 	} else {
145 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
146 		IEEE80211_ADDR_COPY(wh->i_addr1, da);
147 		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
148 		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
149 	}
150 
151 	*(u_int16_t *)&wh->i_dur[0] = 0;
152 	/* NB: use non-QoS tid */
153 	*(u_int16_t *)&wh->i_seq[0] =
154 	    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
155 	ni->ni_txseqs[0]++;
156 #undef WH4
157 }
158 
159 /*
160  * Send a management frame to the specified node.  The node pointer
161  * must have a reference as the pointer will be passed to the driver
162  * and potentially held for a long time.  If the frame is successfully
163  * dispatched to the driver, then it is responsible for freeing the
164  * reference (and potentially free'ing up any associated storage).
165  */
166 static int
ieee80211_mgmt_output(struct ieee80211com * ic,struct ieee80211_node * ni,struct mbuf * m,int type,int timer)167 ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
168     struct mbuf *m, int type, int timer)
169 {
170 	struct ifnet *ifp = ic->ic_ifp;
171 	struct ieee80211_frame *wh;
172 
173 	IASSERT(ni != NULL, ("null node"));
174 
175 	/*
176 	 * Yech, hack alert!  We want to pass the node down to the
177 	 * driver's start routine.  If we don't do so then the start
178 	 * routine must immediately look it up again and that can
179 	 * cause a lock order reversal if, for example, this frame
180 	 * is being sent because the station is being timedout and
181 	 * the frame being sent is a DEAUTH message.  We could stick
182 	 * this in an m_tag and tack that on to the mbuf.  However
183 	 * that's rather expensive to do for every frame so instead
184 	 * we stuff it in the rcvif field since outbound frames do
185 	 * not (presently) use this.
186 	 */
187 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
188 	if (m == NULL)
189 		return ENOMEM;
190 	M_SETCTX(m, ni);
191 
192 	wh = mtod(m, struct ieee80211_frame *);
193 	ieee80211_send_setup(ic, ni, wh, IEEE80211_FC0_TYPE_MGT | type,
194 	    ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
195 
196 	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
197 		m->m_flags &= ~M_LINK0;
198 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
199 			"[%s] encrypting frame (%s)\n",
200 			ether_sprintf(wh->i_addr1), __func__);
201 		wh->i_fc[1] |= IEEE80211_FC1_WEP;
202 	}
203 
204 #ifdef IEEE80211_DEBUG
205 	/* avoid printing too many frames */
206 	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
207 	    ieee80211_msg_dumppkts(ic)) {
208 		printf("[%s] send %s on channel %u\n",
209 		    ether_sprintf(wh->i_addr1),
210 		    ieee80211_mgt_subtype_name[
211 			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
212 				IEEE80211_FC0_SUBTYPE_SHIFT],
213 		    ieee80211_chan2ieee(ic, ic->ic_curchan));
214 	}
215 #endif
216 
217 	IEEE80211_NODE_STAT(ni, tx_mgmt);
218 	IF_ENQUEUE(&ic->ic_mgtq, m);
219 	if (timer) {
220 		/*
221 		 * Set the mgt frame timeout.
222 		 */
223 		ic->ic_mgt_timer = timer;
224 		ifp->if_timer = 1;
225 	}
226 	if_start_lock(ifp);
227 	return 0;
228 }
229 
230 /*
231  * Send a null data frame to the specified node.
232  *
233  * NB: the caller is assumed to have setup a node reference
234  *     for use; this is necessary to deal with a race condition
235  *     when probing for inactive stations.
236  */
237 int
ieee80211_send_nulldata(struct ieee80211_node * ni)238 ieee80211_send_nulldata(struct ieee80211_node *ni)
239 {
240 	struct ieee80211com *ic = ni->ni_ic;
241 	struct ifnet *ifp = ic->ic_ifp;
242 	struct mbuf *m;
243 	struct ieee80211_frame *wh;
244 
245 	MGETHDR(m, M_NOWAIT, MT_HEADER);
246 	if (m == NULL) {
247 		ic->ic_stats.is_tx_nobuf++;
248 		ieee80211_unref_node(&ni);
249 		return ENOMEM;
250 	}
251 	M_SETCTX(m, ni);
252 
253 	wh = mtod(m, struct ieee80211_frame *);
254 
255 	ieee80211_send_setup(ic, ni, wh,
256 	    IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
257 	    ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
258 
259 	/* NB: power management bit is never sent by an AP */
260 	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
261 	    ic->ic_opmode != IEEE80211_M_HOSTAP) {
262 		wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
263 	}
264 
265 	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
266 
267 	IEEE80211_NODE_STAT(ni, tx_data);
268 
269 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
270 	    "[%s] send null data frame on channel %u, pwr mgt %s\n",
271 	    ether_sprintf(ni->ni_macaddr),
272 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
273 	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
274 
275 	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
276 	if_start_lock(ifp);
277 
278 	return 0;
279 }
280 
281 /*
282  * Assign priority to a frame based on any vlan tag assigned
283  * to the station and/or any Diffserv setting in an IP header.
284  * Finally, if an ACM policy is setup (in station mode) it's
285  * applied.
286  */
287 int
ieee80211_classify(struct ieee80211com * ic,struct mbuf * m,struct ieee80211_node * ni)288 ieee80211_classify(struct ieee80211com *ic, struct mbuf *m,
289     struct ieee80211_node *ni)
290 {
291 	int v_wme_ac, d_wme_ac, ac;
292 #ifdef INET
293 	struct ether_header *eh;
294 #endif
295 
296 	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
297 		ac = WME_AC_BE;
298 		goto done;
299 	}
300 
301 	/*
302 	 * If node has a vlan tag then all traffic
303 	 * to it must have a matching tag.
304 	 */
305 	v_wme_ac = 0;
306 	if (ni->ni_vlan != 0) {
307 		/* XXX used to check ec_nvlans. */
308 		if (!vlan_has_tag(m)) {
309 			IEEE80211_NODE_STAT(ni, tx_novlantag);
310 			return 1;
311 		}
312 		if (EVL_VLANOFTAG(vlan_get_tag(m)) !=
313 		    EVL_VLANOFTAG(ni->ni_vlan)) {
314 			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
315 			return 1;
316 		}
317 		/* map vlan priority to AC */
318 		switch (EVL_PRIOFTAG(ni->ni_vlan)) {
319 		case 1:
320 		case 2:
321 			v_wme_ac = WME_AC_BK;
322 			break;
323 		case 0:
324 		case 3:
325 			v_wme_ac = WME_AC_BE;
326 			break;
327 		case 4:
328 		case 5:
329 			v_wme_ac = WME_AC_VI;
330 			break;
331 		case 6:
332 		case 7:
333 			v_wme_ac = WME_AC_VO;
334 			break;
335 		}
336 	}
337 
338 #ifdef INET
339 	eh = mtod(m, struct ether_header *);
340 	if (eh->ether_type == htons(ETHERTYPE_IP)) {
341 		const struct ip *ip = (struct ip *)
342 			(mtod(m, u_int8_t *) + sizeof (*eh));
343 		/*
344 		 * IP frame, map the TOS field.
345 		 */
346 		switch (ip->ip_tos) {
347 		case 0x08:
348 		case 0x20:
349 			d_wme_ac = WME_AC_BK;	/* background */
350 			break;
351 		case 0x28:
352 		case 0xa0:
353 			d_wme_ac = WME_AC_VI;	/* video */
354 			break;
355 		case 0x30:			/* voice */
356 		case 0xe0:
357 		case 0x88:			/* XXX UPSD */
358 		case 0xb8:
359 			d_wme_ac = WME_AC_VO;
360 			break;
361 		default:
362 			d_wme_ac = WME_AC_BE;
363 			break;
364 		}
365 	} else {
366 #endif /* INET */
367 		d_wme_ac = WME_AC_BE;
368 #ifdef INET
369 	}
370 #endif
371 	/*
372 	 * Use highest priority AC.
373 	 */
374 	if (v_wme_ac > d_wme_ac)
375 		ac = v_wme_ac;
376 	else
377 		ac = d_wme_ac;
378 
379 	/*
380 	 * Apply ACM policy.
381 	 */
382 	if (ic->ic_opmode == IEEE80211_M_STA) {
383 		static const int acmap[4] = {
384 			WME_AC_BK,	/* WME_AC_BE */
385 			WME_AC_BK,	/* WME_AC_BK */
386 			WME_AC_BE,	/* WME_AC_VI */
387 			WME_AC_VI,	/* WME_AC_VO */
388 		};
389 		while (ac != WME_AC_BK &&
390 		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
391 			ac = acmap[ac];
392 	}
393 done:
394 	M_WME_SETAC(m, ac);
395 	return 0;
396 }
397 
398 /*
399  * Insure there is sufficient contiguous space to encapsulate the
400  * 802.11 data frame.  If room isn't already there, arrange for it.
401  * Drivers and cipher modules assume we have done the necessary work
402  * and fail rudely if they don't find the space they need.
403  *
404  * Basically, we are trying to make sure that the several M_PREPENDs
405  * called after this function do not fail.
406  */
407 static struct mbuf *
ieee80211_mbuf_adjust(struct ieee80211com * ic,int hdrsize,struct ieee80211_key * key,struct mbuf * m)408 ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
409 	struct ieee80211_key *key, struct mbuf *m)
410 {
411 #define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
412 	int needed_space = hdrsize;
413 	int wlen = 0;
414 
415 	if (key != NULL) {
416 		/* XXX belongs in crypto code? */
417 		needed_space += key->wk_cipher->ic_header;
418 		/* XXX frags */
419 	}
420 
421 	/*
422 	 * We know we are called just before stripping an Ethernet
423 	 * header and prepending an LLC header.  This means we know
424 	 * there will be
425 	 *	sizeof(struct ether_header) - sizeof(struct llc)
426 	 * bytes recovered to which we need additional space for the
427 	 * 802.11 header and any crypto header.
428 	 */
429 	/* XXX check trailing space and copy instead? */
430 	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
431 		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
432 		if (n == NULL) {
433 			ic->ic_stats.is_tx_nobuf++;
434 			m_freem(m);
435 			return NULL;
436 		}
437 
438 		IASSERT(needed_space <= MHLEN,
439 		    ("not enough room, need %u got %lu\n", needed_space, (u_long)MHLEN));
440 
441 		/*
442 		 * Setup new mbuf to have leading space to prepend the
443 		 * 802.11 header and any crypto header bits that are
444 		 * required (the latter are added when the driver calls
445 		 * back to ieee80211_crypto_encap to do crypto encapsulation).
446 		 */
447 		m_move_pkthdr(n, m);
448 		n->m_len = 0;
449 		n->m_data += needed_space;
450 
451 		/*
452 		 * Pull up Ethernet header to create the expected layout.
453 		 * We could use m_pullup but that's overkill (i.e. we don't
454 		 * need the actual data) and it cannot fail so do it inline
455 		 * for speed.
456 		 */
457 		n->m_len += sizeof(struct ether_header);
458 		m->m_len -= sizeof(struct ether_header);
459 		m->m_data += sizeof(struct ether_header);
460 
461 		/*
462 		 * Replace the head of the chain.
463 		 */
464 		n->m_next = m;
465 		m = n;
466 	} else {
467 		/*
468 		 * We will overwrite the ethernet header in the
469 		 * 802.11 encapsulation stage.  Make sure that it
470 		 * is writable.
471 		 */
472 		wlen = sizeof(struct ether_header);
473 	}
474 
475 	/*
476 	 * If we're going to s/w encrypt the mbuf chain make sure it is
477 	 * writable.
478 	 */
479 	if (key != NULL && (key->wk_flags & IEEE80211_KEY_SWCRYPT) != 0) {
480 		wlen = M_COPYALL;
481 	}
482 	if (wlen != 0 && m_makewritable(&m, 0, wlen, M_DONTWAIT) != 0) {
483 		m_freem(m);
484 		return NULL;
485 	}
486 
487 	return m;
488 #undef TO_BE_RECLAIMED
489 }
490 
491 /*
492  * Return the transmit key to use in sending a unicast frame.
493  * If a unicast key is set we use that.  When no unicast key is set
494  * we fall back to the default transmit key.
495  */
496 static __inline struct ieee80211_key *
ieee80211_crypto_getucastkey(struct ieee80211com * ic,struct ieee80211_node * ni)497 ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
498 {
499 	if (IEEE80211_KEY_UNDEFINED(ni->ni_ucastkey)) {
500 		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
501 		    IEEE80211_KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
502 			return NULL;
503 		return &ic->ic_nw_keys[ic->ic_def_txkey];
504 	} else {
505 		return &ni->ni_ucastkey;
506 	}
507 }
508 
509 /*
510  * Return the transmit key to use in sending a multicast frame.
511  * Multicast traffic always uses the group key which is installed as
512  * the default tx key.
513  */
514 static __inline struct ieee80211_key *
ieee80211_crypto_getmcastkey(struct ieee80211com * ic,struct ieee80211_node * ni)515 ieee80211_crypto_getmcastkey(struct ieee80211com *ic,
516     struct ieee80211_node *ni)
517 {
518 	if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
519 	    IEEE80211_KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
520 		return NULL;
521 	return &ic->ic_nw_keys[ic->ic_def_txkey];
522 }
523 
524 /*
525  * Encapsulate an outbound data frame.  The mbuf chain is updated.
526  * If an error is encountered NULL is returned.  The caller is required
527  * to provide a node reference and pullup the ethernet header in the
528  * first mbuf.
529  */
530 struct mbuf *
ieee80211_encap(struct ieee80211com * ic,struct mbuf * m,struct ieee80211_node * ni)531 ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
532 	struct ieee80211_node *ni)
533 {
534 	struct ether_header eh;
535 	struct ieee80211_frame *wh;
536 	struct ieee80211_key *key;
537 	struct llc *llc;
538 	int hdrsize, datalen, addqos, txfrag;
539 
540 	IASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
541 	memcpy(&eh, mtod(m, void *), sizeof(struct ether_header));
542 
543 	/*
544 	 * Insure space for additional headers.  First identify
545 	 * transmit key to use in calculating any buffer adjustments
546 	 * required.  This is also used below to do privacy
547 	 * encapsulation work.  Then calculate the 802.11 header
548 	 * size and any padding required by the driver.
549 	 *
550 	 * Note key may be NULL if we fall back to the default
551 	 * transmit key and that is not set.  In that case the
552 	 * buffer may not be expanded as needed by the cipher
553 	 * routines, but they will/should discard it.
554 	 */
555 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
556 		if (ic->ic_opmode == IEEE80211_M_STA ||
557 		    !IEEE80211_IS_MULTICAST(eh.ether_dhost)) {
558 			key = ieee80211_crypto_getucastkey(ic, ni);
559 		} else {
560 			key = ieee80211_crypto_getmcastkey(ic, ni);
561 		}
562 		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
563 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
564 			    "[%s] no default transmit key (%s) deftxkey %u\n",
565 			    ether_sprintf(eh.ether_dhost), __func__,
566 			    ic->ic_def_txkey);
567 			ic->ic_stats.is_tx_nodefkey++;
568 		}
569 	} else {
570 		key = NULL;
571 	}
572 
573 	/*
574 	 * XXX 4-address format.
575 	 *
576 	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
577 	 * frames so suppress use.  This may be an issue if other
578 	 * ap's require all data frames to be QoS-encapsulated
579 	 * once negotiated in which case we'll need to make this
580 	 * configurable.
581 	 */
582 	addqos = (ni->ni_flags & IEEE80211_NODE_QOS) &&
583 	    eh.ether_type != htons(ETHERTYPE_PAE);
584 	if (addqos)
585 		hdrsize = sizeof(struct ieee80211_qosframe);
586 	else
587 		hdrsize = sizeof(struct ieee80211_frame);
588 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
589 		hdrsize = roundup(hdrsize, sizeof(u_int32_t));
590 
591 	m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
592 	if (m == NULL) {
593 		/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
594 		goto bad;
595 	}
596 
597 	/* NB: this could be optimized because of ieee80211_mbuf_adjust */
598 	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
599 	llc = mtod(m, struct llc *);
600 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
601 	llc->llc_control = LLC_UI;
602 	llc->llc_snap.org_code[0] = 0;
603 	llc->llc_snap.org_code[1] = 0;
604 	llc->llc_snap.org_code[2] = 0;
605 	llc->llc_snap.ether_type = eh.ether_type;
606 	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
607 
608 	M_PREPEND(m, hdrsize, M_DONTWAIT);
609 	if (m == NULL) {
610 		ic->ic_stats.is_tx_nobuf++;
611 		goto bad;
612 	}
613 
614 	wh = mtod(m, struct ieee80211_frame *);
615 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
616 	*(u_int16_t *)wh->i_dur = 0;
617 
618 	switch (ic->ic_opmode) {
619 	case IEEE80211_M_STA:
620 		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
621 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
622 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
623 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
624 		break;
625 
626 	case IEEE80211_M_IBSS:
627 	case IEEE80211_M_AHDEMO:
628 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
629 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
630 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
631 		/*
632 		 * NB: always use the bssid from ic_bss as the
633 		 *     neighbor's may be stale after an ibss merge
634 		 */
635 		IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
636 		break;
637 
638 	case IEEE80211_M_HOSTAP:
639 #ifndef IEEE80211_NO_HOSTAP
640 		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
641 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
642 		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
643 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
644 #endif
645 		break;
646 
647 	case IEEE80211_M_MONITOR:
648 		goto bad;
649 	}
650 
651 	if (m->m_flags & M_MORE_DATA)
652 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
653 
654 	if (addqos) {
655 		struct ieee80211_qosframe *qwh =
656 			(struct ieee80211_qosframe *)wh;
657 		int ac, tid;
658 
659 		ac = M_WME_GETAC(m);
660 		/* map from access class/queue to 11e header priorty value */
661 		tid = WME_AC_TO_TID(ac);
662 		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
663 		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
664 			qwh->i_qos[0] |= 1 << IEEE80211_QOS_ACKPOLICY_S;
665 		qwh->i_qos[1] = 0;
666 		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
667 
668 		*(u_int16_t *)wh->i_seq =
669 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
670 		ni->ni_txseqs[tid]++;
671 	} else {
672 		*(u_int16_t *)wh->i_seq =
673 		    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
674 		ni->ni_txseqs[0]++;
675 	}
676 
677 	/* check if xmit fragmentation is required */
678 	txfrag = (m->m_pkthdr.len > ic->ic_fragthreshold &&
679 	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
680 	    (m->m_flags & M_FF) == 0);          /* NB: don't fragment ff's */
681 
682 	if (key != NULL) {
683 		/*
684 		 * IEEE 802.1X: send EAPOL frames always in the clear.
685 		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
686 		 */
687 		if (eh.ether_type != htons(ETHERTYPE_PAE) ||
688 		    ((ic->ic_flags & IEEE80211_F_WPA) &&
689 		     (ic->ic_opmode == IEEE80211_M_STA ?
690 		      !IEEE80211_KEY_UNDEFINED(*key) :
691 		      !IEEE80211_KEY_UNDEFINED(ni->ni_ucastkey)))) {
692 			wh->i_fc[1] |= IEEE80211_FC1_WEP;
693 			if (!ieee80211_crypto_enmic(ic, key, m, txfrag)) {
694 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
695 				    "[%s] enmic failed, discard frame\n",
696 				    ether_sprintf(eh.ether_dhost));
697 				ic->ic_stats.is_crypto_enmicfail++;
698 				goto bad;
699 			}
700 		}
701 	}
702 
703 	if (txfrag && !ieee80211_fragment(ic, m, hdrsize,
704 	    key != NULL ? key->wk_cipher->ic_header : 0, ic->ic_fragthreshold))
705 		goto bad;
706 
707 	IEEE80211_NODE_STAT(ni, tx_data);
708 	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
709 
710 	return m;
711 
712 bad:
713 	m_freem(m);
714 	return NULL;
715 }
716 
717 /*
718  * Arguments in:
719  *
720  * paylen:  payload length (no FCS, no WEP header)
721  *
722  * hdrlen:  header length
723  *
724  * rate:    MSDU speed, units 500kb/s
725  *
726  * flags:   IEEE80211_F_SHPREAMBLE (use short preamble),
727  *          IEEE80211_F_SHSLOT (use short slot length)
728  *
729  * Arguments out:
730  *
731  * d:       802.11 Duration field for RTS,
732  *          802.11 Duration field for data frame,
733  *          PLCP Length for data frame,
734  *          residual octets at end of data slot
735  */
736 static int
ieee80211_compute_duration1(int len,int use_ack,uint32_t icflags,int rate,struct ieee80211_duration * d)737 ieee80211_compute_duration1(int len, int use_ack, uint32_t icflags, int rate,
738     struct ieee80211_duration *d)
739 {
740 	int pre, ctsrate;
741 	int ack, bitlen, data_dur, remainder;
742 
743 	/* RTS reserves medium for SIFS | CTS | SIFS | (DATA) | SIFS | ACK
744 	 * DATA reserves medium for SIFS | ACK,
745 	 *
746 	 * (XXX or SIFS | ACK | SIFS | DATA | SIFS | ACK, if more fragments)
747 	 *
748 	 * XXXMYC: no ACK on multicast/broadcast or control packets
749 	 */
750 
751 	bitlen = len * 8;
752 
753 	pre = IEEE80211_DUR_DS_SIFS;
754 	if ((icflags & IEEE80211_F_SHPREAMBLE) != 0)
755 		pre += IEEE80211_DUR_DS_SHORT_PREAMBLE + IEEE80211_DUR_DS_FAST_PLCPHDR;
756 	else
757 		pre += IEEE80211_DUR_DS_LONG_PREAMBLE + IEEE80211_DUR_DS_SLOW_PLCPHDR;
758 
759 	d->d_residue = 0;
760 	data_dur = (bitlen * 2) / rate;
761 	remainder = (bitlen * 2) % rate;
762 	if (remainder != 0) {
763 		d->d_residue = (rate - remainder) / 16;
764 		data_dur++;
765 	}
766 
767 	switch (rate) {
768 	case 2:		/* 1 Mb/s */
769 	case 4:		/* 2 Mb/s */
770 		/* 1 - 2 Mb/s WLAN: send ACK/CTS at 1 Mb/s */
771 		ctsrate = 2;
772 		break;
773 	case 11:	/* 5.5 Mb/s */
774 	case 22:	/* 11  Mb/s */
775 	case 44:	/* 22  Mb/s */
776 		/* 5.5 - 11 Mb/s WLAN: send ACK/CTS at 2 Mb/s */
777 		ctsrate = 4;
778 		break;
779 	default:
780 		/* TBD */
781 		return -1;
782 	}
783 
784 	d->d_plcp_len = data_dur;
785 
786 	ack = (use_ack) ? pre + (IEEE80211_DUR_DS_SLOW_ACK * 2) / ctsrate : 0;
787 
788 	d->d_rts_dur =
789 	    pre + (IEEE80211_DUR_DS_SLOW_CTS * 2) / ctsrate +
790 	    pre + data_dur +
791 	    ack;
792 
793 	d->d_data_dur = ack;
794 
795 	return 0;
796 }
797 
798 /*
799  * Arguments in:
800  *
801  * wh:      802.11 header
802  *
803  * paylen:  payload length (no FCS, no WEP header)
804  *
805  * rate:    MSDU speed, units 500kb/s
806  *
807  * fraglen: fragment length, set to maximum (or higher) for no
808  *          fragmentation
809  *
810  * flags:   IEEE80211_F_PRIVACY (hardware adds WEP),
811  *          IEEE80211_F_SHPREAMBLE (use short preamble),
812  *          IEEE80211_F_SHSLOT (use short slot length)
813  *
814  * Arguments out:
815  *
816  * d0: 802.11 Duration fields (RTS/Data), PLCP Length, Service fields
817  *     of first/only fragment
818  *
819  * dn: 802.11 Duration fields (RTS/Data), PLCP Length, Service fields
820  *     of last fragment
821  *
822  * ieee80211_compute_duration assumes crypto-encapsulation, if any,
823  * has already taken place.
824  */
825 int
ieee80211_compute_duration(const struct ieee80211_frame_min * wh,const struct ieee80211_key * wk,int len,uint32_t icflags,int fraglen,int rate,struct ieee80211_duration * d0,struct ieee80211_duration * dn,int * npktp,int debug)826 ieee80211_compute_duration(const struct ieee80211_frame_min *wh,
827     const struct ieee80211_key *wk, int len,
828     uint32_t icflags, int fraglen, int rate, struct ieee80211_duration *d0,
829     struct ieee80211_duration *dn, int *npktp, int debug)
830 {
831 	int ack, rc;
832 	int cryptolen,	/* crypto overhead: header+trailer */
833 	    firstlen,	/* first fragment's payload + overhead length */
834 	    hdrlen,	/* header length w/o driver padding */
835 	    lastlen,	/* last fragment's payload length w/ overhead */
836 	    lastlen0,	/* last fragment's payload length w/o overhead */
837 	    npkt,	/* number of fragments */
838 	    overlen,	/* non-802.11 header overhead per fragment */
839 	    paylen;	/* payload length w/o overhead */
840 
841 	hdrlen = ieee80211_anyhdrsize((const void *)wh);
842 
843 	/* Account for padding required by the driver. */
844 	if (icflags & IEEE80211_F_DATAPAD) {
845 		paylen = len - roundup(hdrlen, sizeof(u_int32_t));
846 		if (paylen < 0) {
847 			panic("%s: paylen < 0", __func__);
848 		}
849 	} else {
850 		paylen = len - hdrlen;
851 	}
852 
853 	overlen = IEEE80211_CRC_LEN;
854 
855 	if (wk != NULL) {
856 		cryptolen = wk->wk_cipher->ic_header +
857 		            wk->wk_cipher->ic_trailer;
858 		paylen -= cryptolen;
859 		overlen += cryptolen;
860 	}
861 
862 	npkt = paylen / fraglen;
863 	lastlen0 = paylen % fraglen;
864 
865 	if (npkt == 0)			/* no fragments */
866 		lastlen = paylen + overlen;
867 	else if (lastlen0 != 0) {	/* a short "tail" fragment */
868 		lastlen = lastlen0 + overlen;
869 		npkt++;
870 	} else				/* full-length "tail" fragment */
871 		lastlen = fraglen + overlen;
872 
873 	if (npktp != NULL)
874 		*npktp = npkt;
875 
876 	if (npkt > 1)
877 		firstlen = fraglen + overlen;
878 	else
879 		firstlen = paylen + overlen;
880 
881 	if (debug) {
882 		printf("%s: npkt %d firstlen %d lastlen0 %d lastlen %d "
883 		    "fraglen %d overlen %d len %d rate %d icflags %08x\n",
884 		    __func__, npkt, firstlen, lastlen0, lastlen, fraglen,
885 		    overlen, len, rate, icflags);
886 	}
887 
888 	ack = !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
889 	    (wh->i_fc[1] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL;
890 
891 	rc = ieee80211_compute_duration1(firstlen + hdrlen,
892 	    ack, icflags, rate, d0);
893 	if (rc == -1)
894 		return rc;
895 
896 	if (npkt <= 1) {
897 		*dn = *d0;
898 		return 0;
899 	}
900 	return ieee80211_compute_duration1(lastlen + hdrlen, ack, icflags, rate,
901 	    dn);
902 }
903 
904 /*
905  * Fragment the frame according to the specified mtu.
906  * The size of the 802.11 header (w/o padding) is provided
907  * so we don't need to recalculate it.  We create a new
908  * mbuf for each fragment and chain it through m_nextpkt;
909  * we might be able to optimize this by reusing the original
910  * packet's mbufs but that is significantly more complicated.
911  */
912 static int
ieee80211_fragment(struct ieee80211com * ic,struct mbuf * m0,u_int hdrsize,u_int ciphdrsize,u_int mtu)913 ieee80211_fragment(struct ieee80211com *ic, struct mbuf *m0,
914 	u_int hdrsize, u_int ciphdrsize, u_int mtu)
915 {
916 	struct ieee80211_frame *wh, *whf;
917 	struct mbuf *m, *prev, *next;
918 	const u_int totalhdrsize = hdrsize + ciphdrsize;
919 	u_int fragno, fragsize, off, remainder, payload;
920 
921 	IASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
922 	IASSERT(m0->m_pkthdr.len > mtu,
923 		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
924 
925 	wh = mtod(m0, struct ieee80211_frame *);
926 	/* NB: mark the first frag; it will be propagated below */
927 	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
928 
929 	fragno = 1;
930 	off = mtu - ciphdrsize;
931 	remainder = m0->m_pkthdr.len - off;
932 	prev = m0;
933 	do {
934 		fragsize = totalhdrsize + remainder;
935 		if (fragsize > mtu)
936 			fragsize = mtu;
937 		IASSERT(fragsize < MCLBYTES,
938 			("fragment size %u too big!", fragsize));
939 		if (fragsize > MHLEN)
940 			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
941 		else
942 			m = m_gethdr(M_DONTWAIT, MT_DATA);
943 		if (m == NULL)
944 			goto bad;
945 
946 		/* leave room to prepend any cipher header */
947 		m_align(m, fragsize - ciphdrsize);
948 
949 		/*
950 		 * Form the header in the fragment.  Note that since
951 		 * we mark the first fragment with the MORE_FRAG bit
952 		 * it automatically is propagated to each fragment; we
953 		 * need only clear it on the last fragment (done below).
954 		 */
955 		whf = mtod(m, struct ieee80211_frame *);
956 		memcpy(whf, wh, hdrsize);
957 		*(u_int16_t *)&whf->i_seq[0] |= htole16(
958 			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
959 				IEEE80211_SEQ_FRAG_SHIFT);
960 		fragno++;
961 
962 		payload = fragsize - totalhdrsize;
963 		/* NB: destination is known to be contiguous */
964 		m_copydata(m0, off, payload, mtod(m, u_int8_t *) + hdrsize);
965 		m->m_len = hdrsize + payload;
966 		m->m_pkthdr.len = hdrsize + payload;
967 		m->m_flags |= M_FRAG;
968 
969 		/* chain up the fragment */
970 		prev->m_nextpkt = m;
971 		prev = m;
972 
973 		/* deduct fragment just formed */
974 		remainder -= payload;
975 		off += payload;
976 	} while (remainder != 0);
977 
978 	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
979 
980 	/* strip first mbuf now that everything has been copied */
981 	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
982 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
983 
984 	ic->ic_stats.is_tx_fragframes++;
985 	ic->ic_stats.is_tx_frags += fragno-1;
986 
987 	return 1;
988 
989 bad:
990 	/* reclaim fragments but leave original frame for caller to free */
991 	for (m = m0->m_nextpkt; m != NULL; m = next) {
992 		next = m->m_nextpkt;
993 		m->m_nextpkt = NULL;
994 		m_freem(m);
995 	}
996 	m0->m_nextpkt = NULL;
997 
998 	return 0;
999 }
1000 
1001 /*
1002  * Add a supported rates element id to a frame.
1003  */
1004 u_int8_t *
ieee80211_add_rates(u_int8_t * frm,const struct ieee80211_rateset * rs)1005 ieee80211_add_rates(u_int8_t *frm, const struct ieee80211_rateset *rs)
1006 {
1007 	int nrates;
1008 
1009 	*frm++ = IEEE80211_ELEMID_RATES;
1010 	nrates = rs->rs_nrates;
1011 	if (nrates > IEEE80211_RATE_SIZE)
1012 		nrates = IEEE80211_RATE_SIZE;
1013 	*frm++ = nrates;
1014 	memcpy(frm, rs->rs_rates, nrates);
1015 	return frm + nrates;
1016 }
1017 
1018 /*
1019  * Add an extended supported rates element id to a frame.
1020  */
1021 u_int8_t *
ieee80211_add_xrates(u_int8_t * frm,const struct ieee80211_rateset * rs)1022 ieee80211_add_xrates(u_int8_t *frm, const struct ieee80211_rateset *rs)
1023 {
1024 	/*
1025 	 * Add an extended supported rates element if operating in 11g mode.
1026 	 */
1027 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
1028 		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
1029 		*frm++ = IEEE80211_ELEMID_XRATES;
1030 		*frm++ = nrates;
1031 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
1032 		frm += nrates;
1033 	}
1034 	return frm;
1035 }
1036 
1037 /*
1038  * Add an ssid elemet to a frame.
1039  */
1040 u_int8_t *
ieee80211_add_ssid(u_int8_t * frm,const u_int8_t * ssid,u_int len)1041 ieee80211_add_ssid(u_int8_t *frm, const u_int8_t *ssid, u_int len)
1042 {
1043 	*frm++ = IEEE80211_ELEMID_SSID;
1044 	*frm++ = len;
1045 	memcpy(frm, ssid, len);
1046 	return frm + len;
1047 }
1048 
1049 /*
1050  * Add an erp element to a frame.
1051  */
1052 static u_int8_t *
ieee80211_add_erp(u_int8_t * frm,struct ieee80211com * ic)1053 ieee80211_add_erp(u_int8_t *frm, struct ieee80211com *ic)
1054 {
1055 	u_int8_t erp;
1056 
1057 	*frm++ = IEEE80211_ELEMID_ERP;
1058 	*frm++ = 1;
1059 	erp = 0;
1060 	if (ic->ic_nonerpsta != 0)
1061 		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
1062 	if (ic->ic_flags & IEEE80211_F_USEPROT)
1063 		erp |= IEEE80211_ERP_USE_PROTECTION;
1064 	if (ic->ic_flags & IEEE80211_F_USEBARKER)
1065 		erp |= IEEE80211_ERP_LONG_PREAMBLE;
1066 	*frm++ = erp;
1067 	return frm;
1068 }
1069 
1070 static u_int8_t *
ieee80211_setup_wpa_ie(struct ieee80211com * ic,u_int8_t * ie)1071 ieee80211_setup_wpa_ie(struct ieee80211com *ic, u_int8_t *ie)
1072 {
1073 #define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
1074 #define	ADDSHORT(frm, v) do {			\
1075 	frm[0] = (v) & 0xff;			\
1076 	frm[1] = (v) >> 8;			\
1077 	frm += 2;				\
1078 } while (0)
1079 #define	ADDSELECTOR(frm, sel) do {		\
1080 	memcpy(frm, sel, 4);			\
1081 	frm += 4;				\
1082 } while (0)
1083 	static const u_int8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
1084 	static const u_int8_t cipher_suite[][4] = {
1085 		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
1086 		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
1087 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
1088 		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
1089 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
1090 		{ WPA_OUI_BYTES, WPA_CSE_NULL },
1091 	};
1092 	static const u_int8_t wep104_suite[4] =
1093 		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
1094 	static const u_int8_t key_mgt_unspec[4] =
1095 		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
1096 	static const u_int8_t key_mgt_psk[4] =
1097 		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
1098 	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
1099 	u_int8_t *frm = ie;
1100 	u_int8_t *selcnt;
1101 
1102 	*frm++ = IEEE80211_ELEMID_VENDOR;
1103 	*frm++ = 0;				/* length filled in below */
1104 	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
1105 	frm += sizeof(oui);
1106 	ADDSHORT(frm, WPA_VERSION);
1107 
1108 	/* XXX filter out CKIP */
1109 
1110 	/* multicast cipher */
1111 	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
1112 	    rsn->rsn_mcastkeylen >= 13)
1113 		ADDSELECTOR(frm, wep104_suite);
1114 	else
1115 		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
1116 
1117 	/* unicast cipher list */
1118 	selcnt = frm;
1119 	ADDSHORT(frm, 0);			/* selector count */
1120 	if (rsn->rsn_ucastcipherset & (1 << IEEE80211_CIPHER_AES_CCM)) {
1121 		selcnt[0]++;
1122 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
1123 	}
1124 	if (rsn->rsn_ucastcipherset & (1 << IEEE80211_CIPHER_TKIP)) {
1125 		selcnt[0]++;
1126 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
1127 	}
1128 
1129 	/* authenticator selector list */
1130 	selcnt = frm;
1131 	ADDSHORT(frm, 0);			/* selector count */
1132 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
1133 		selcnt[0]++;
1134 		ADDSELECTOR(frm, key_mgt_unspec);
1135 	}
1136 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
1137 		selcnt[0]++;
1138 		ADDSELECTOR(frm, key_mgt_psk);
1139 	}
1140 
1141 	/* optional capabilities */
1142 	if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
1143 		ADDSHORT(frm, rsn->rsn_caps);
1144 
1145 	/* calculate element length */
1146 	ie[1] = frm - ie - 2;
1147 	IASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1148 		("WPA IE too big, %u > %zu",
1149 		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1150 	return frm;
1151 #undef ADDSHORT
1152 #undef ADDSELECTOR
1153 #undef WPA_OUI_BYTES
1154 }
1155 
1156 static u_int8_t *
ieee80211_setup_rsn_ie(struct ieee80211com * ic,u_int8_t * ie)1157 ieee80211_setup_rsn_ie(struct ieee80211com *ic, u_int8_t *ie)
1158 {
1159 #define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
1160 #define	ADDSHORT(frm, v) do {			\
1161 	frm[0] = (v) & 0xff;			\
1162 	frm[1] = (v) >> 8;			\
1163 	frm += 2;				\
1164 } while (0)
1165 #define	ADDSELECTOR(frm, sel) do {		\
1166 	memcpy(frm, sel, 4);			\
1167 	frm += 4;				\
1168 } while (0)
1169 	static const u_int8_t cipher_suite[][4] = {
1170 		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
1171 		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
1172 		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
1173 		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
1174 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
1175 		{ RSN_OUI_BYTES, RSN_CSE_NULL },
1176 	};
1177 	static const u_int8_t wep104_suite[4] =
1178 		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
1179 	static const u_int8_t key_mgt_unspec[4] =
1180 		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
1181 	static const u_int8_t key_mgt_psk[4] =
1182 		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
1183 	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
1184 	u_int8_t *frm = ie;
1185 	u_int8_t *selcnt;
1186 
1187 	*frm++ = IEEE80211_ELEMID_RSN;
1188 	*frm++ = 0;				/* length filled in below */
1189 	ADDSHORT(frm, RSN_VERSION);
1190 
1191 	/* XXX filter out CKIP */
1192 
1193 	/* multicast cipher */
1194 	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
1195 	    rsn->rsn_mcastkeylen >= 13)
1196 		ADDSELECTOR(frm, wep104_suite);
1197 	else
1198 		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
1199 
1200 	/* unicast cipher list */
1201 	selcnt = frm;
1202 	ADDSHORT(frm, 0);			/* selector count */
1203 	if (rsn->rsn_ucastcipherset & (1 << IEEE80211_CIPHER_AES_CCM)) {
1204 		selcnt[0]++;
1205 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
1206 	}
1207 	if (rsn->rsn_ucastcipherset & (1 << IEEE80211_CIPHER_TKIP)) {
1208 		selcnt[0]++;
1209 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
1210 	}
1211 
1212 	/* authenticator selector list */
1213 	selcnt = frm;
1214 	ADDSHORT(frm, 0);			/* selector count */
1215 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
1216 		selcnt[0]++;
1217 		ADDSELECTOR(frm, key_mgt_unspec);
1218 	}
1219 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
1220 		selcnt[0]++;
1221 		ADDSELECTOR(frm, key_mgt_psk);
1222 	}
1223 
1224 	/* optional capabilities */
1225 	ADDSHORT(frm, rsn->rsn_caps);
1226 	/* XXX PMKID */
1227 
1228 	/* calculate element length */
1229 	ie[1] = frm - ie - 2;
1230 	IASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1231 		("RSN IE too big, %u > %zu",
1232 		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1233 	return frm;
1234 #undef ADDSELECTOR
1235 #undef ADDSHORT
1236 #undef RSN_OUI_BYTES
1237 }
1238 
1239 /*
1240  * Add a WPA/RSN element to a frame.
1241  */
1242 u_int8_t *
ieee80211_add_wpa(u_int8_t * frm,struct ieee80211com * ic)1243 ieee80211_add_wpa(u_int8_t *frm, struct ieee80211com *ic)
1244 {
1245 
1246 	IASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
1247 	if (ic->ic_flags & IEEE80211_F_WPA2)
1248 		frm = ieee80211_setup_rsn_ie(ic, frm);
1249 	if (ic->ic_flags & IEEE80211_F_WPA1)
1250 		frm = ieee80211_setup_wpa_ie(ic, frm);
1251 	return frm;
1252 }
1253 
1254 #define	WME_OUI_BYTES		0x00, 0x50, 0xf2
1255 /*
1256  * Add a WME information element to a frame.
1257  */
1258 u_int8_t *
ieee80211_add_wme_info(u_int8_t * frm,struct ieee80211_wme_state * wme)1259 ieee80211_add_wme_info(u_int8_t *frm, struct ieee80211_wme_state *wme)
1260 {
1261 	static const struct ieee80211_wme_info info = {
1262 		.wme_id		= IEEE80211_ELEMID_VENDOR,
1263 		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
1264 		.wme_oui	= { WME_OUI_BYTES },
1265 		.wme_type	= WME_OUI_TYPE,
1266 		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
1267 		.wme_version	= WME_VERSION,
1268 		.wme_info	= 0,
1269 	};
1270 	memcpy(frm, &info, sizeof(info));
1271 	return frm + sizeof(info);
1272 }
1273 
1274 /*
1275  * Add a WME parameters element to a frame.
1276  */
1277 static u_int8_t *
ieee80211_add_wme_param(u_int8_t * frm,struct ieee80211_wme_state * wme)1278 ieee80211_add_wme_param(u_int8_t *frm, struct ieee80211_wme_state *wme)
1279 {
1280 #define	SM(_v, _f)	(((_v) << _f##_S) & _f)
1281 #define	ADDSHORT(frm, v) do {			\
1282 	frm[0] = (v) & 0xff;			\
1283 	frm[1] = (v) >> 8;			\
1284 	frm += 2;				\
1285 } while (0)
1286 	/* NB: this works because a param has an info at the front */
1287 	static const struct ieee80211_wme_info param = {
1288 		.wme_id		= IEEE80211_ELEMID_VENDOR,
1289 		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
1290 		.wme_oui	= { WME_OUI_BYTES },
1291 		.wme_type	= WME_OUI_TYPE,
1292 		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
1293 		.wme_version	= WME_VERSION,
1294 	};
1295 	int i;
1296 
1297 	memcpy(frm, &param, sizeof(param));
1298 	frm += offsetof(struct ieee80211_wme_info, wme_info);
1299 	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
1300 	*frm++ = 0;					/* reserved field */
1301 	for (i = 0; i < WME_NUM_AC; i++) {
1302 		const struct wmeParams *ac =
1303 		       &wme->wme_bssChanParams.cap_wmeParams[i];
1304 		*frm++ = SM(i, WME_PARAM_ACI) |
1305 		    SM(ac->wmep_acm, WME_PARAM_ACM) |
1306 		    SM(ac->wmep_aifsn, WME_PARAM_AIFSN);
1307 		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX) |
1308 		    SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN);
1309 		ADDSHORT(frm, ac->wmep_txopLimit);
1310 	}
1311 
1312 	return frm;
1313 #undef SM
1314 #undef ADDSHORT
1315 }
1316 #undef WME_OUI_BYTES
1317 
1318 /*
1319  * Send a probe request frame with the specified ssid
1320  * and any optional information element data.
1321  */
1322 int
ieee80211_send_probereq(struct ieee80211_node * ni,const u_int8_t sa[IEEE80211_ADDR_LEN],const u_int8_t da[IEEE80211_ADDR_LEN],const u_int8_t bssid[IEEE80211_ADDR_LEN],const u_int8_t * ssid,size_t ssidlen,const void * optie,size_t optielen)1323 ieee80211_send_probereq(struct ieee80211_node *ni,
1324 	const u_int8_t sa[IEEE80211_ADDR_LEN],
1325 	const u_int8_t da[IEEE80211_ADDR_LEN],
1326 	const u_int8_t bssid[IEEE80211_ADDR_LEN],
1327 	const u_int8_t *ssid, size_t ssidlen,
1328 	const void *optie, size_t optielen)
1329 {
1330 	struct ieee80211com *ic = ni->ni_ic;
1331 	enum ieee80211_phymode mode;
1332 	struct ieee80211_frame *wh;
1333 	struct mbuf *m;
1334 	u_int8_t *frm;
1335 
1336 	/*
1337 	 * Hold a reference on the node so it doesn't go away until after
1338 	 * the xmit is complete all the way in the driver.  On error we
1339 	 * will remove our reference.
1340 	 */
1341 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1342 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1343 		__func__, __LINE__,
1344 		ni, ether_sprintf(ni->ni_macaddr),
1345 		ieee80211_node_refcnt(ni)+1);
1346 	ieee80211_ref_node(ni);
1347 
1348 	/*
1349 	 * prreq frame format
1350 	 *	[tlv] ssid
1351 	 *	[tlv] supported rates
1352 	 *	[tlv] extended supported rates
1353 	 *	[tlv] user-specified ie's
1354 	 */
1355 	m = ieee80211_getmgtframe(&frm,
1356 		 2 + IEEE80211_NWID_LEN
1357 	       + 2 + IEEE80211_RATE_SIZE
1358 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1359 	       + (optie != NULL ? optielen : 0)
1360 	);
1361 	if (m == NULL) {
1362 		ic->ic_stats.is_tx_nobuf++;
1363 		ieee80211_free_node(ni);
1364 		return ENOMEM;
1365 	}
1366 
1367 	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1368 	mode = ieee80211_chan2mode(ic, ic->ic_curchan);
1369 	frm = ieee80211_add_rates(frm, &ic->ic_sup_rates[mode]);
1370 	frm = ieee80211_add_xrates(frm, &ic->ic_sup_rates[mode]);
1371 
1372 	if (optie != NULL) {
1373 		memcpy(frm, optie, optielen);
1374 		frm += optielen;
1375 	}
1376 	m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1377 
1378 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1379 	if (m == NULL) {
1380 		ic->ic_stats.is_tx_nobuf++;
1381 		ieee80211_free_node(ni);
1382 		return ENOMEM;
1383 	}
1384 	M_SETCTX(m, ni);
1385 
1386 	wh = mtod(m, struct ieee80211_frame *);
1387 	ieee80211_send_setup(ic, ni, wh,
1388 	    IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1389 	    sa, da, bssid);
1390 	/* XXX power management? */
1391 
1392 	IEEE80211_NODE_STAT(ni, tx_probereq);
1393 	IEEE80211_NODE_STAT(ni, tx_mgmt);
1394 
1395 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1396 	    "[%s] send probe req on channel %u\n",
1397 	    ether_sprintf(wh->i_addr1),
1398 	    ieee80211_chan2ieee(ic, ic->ic_curchan));
1399 
1400 	IF_ENQUEUE(&ic->ic_mgtq, m);
1401 	if_start_lock(ic->ic_ifp);
1402 	return 0;
1403 }
1404 
1405 /*
1406  * Send a management frame.  The node is for the destination (or ic_bss
1407  * when in station mode).  Nodes other than ic_bss have their reference
1408  * count bumped to reflect our use for an indeterminant time.
1409  */
1410 int
ieee80211_send_mgmt(struct ieee80211com * ic,struct ieee80211_node * ni,int type,int arg)1411 ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
1412 	int type, int arg)
1413 {
1414 #define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
1415 	struct mbuf *m;
1416 	u_int8_t *frm;
1417 	u_int16_t capinfo;
1418 	int ret, timer, status;
1419 
1420 	IASSERT(ni != NULL, ("null node"));
1421 
1422 	/*
1423 	 * Hold a reference on the node so it doesn't go away until after
1424 	 * the xmit is complete all the way in the driver.  On error we
1425 	 * will remove our reference.
1426 	 */
1427 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1428 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1429 		__func__, __LINE__,
1430 		ni, ether_sprintf(ni->ni_macaddr),
1431 		ieee80211_node_refcnt(ni)+1);
1432 	ieee80211_ref_node(ni);
1433 
1434 	timer = 0;
1435 	switch (type) {
1436 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP: {
1437 		const bool has_wpa = (ic->ic_flags & IEEE80211_F_WPA) != 0;
1438 
1439 		/*
1440 		 * probe response frame format
1441 		 *	[8] time stamp
1442 		 *	[2] beacon interval
1443 		 *	[2] cabability information
1444 		 *	[tlv] ssid
1445 		 *	[tlv] supported rates
1446 		 *	[tlv] parameter set (FH/DS)
1447 		 *	[tlv] parameter set (IBSS)
1448 		 *	[tlv] extended rate phy (ERP)
1449 		 *	[tlv] extended supported rates
1450 		 *	[tlv] WPA
1451 		 *	[tlv] WME (optional)
1452 		 */
1453 		m = ieee80211_getmgtframe(&frm,
1454 			 8 /* timestamp */
1455 		       + sizeof(u_int16_t) /* interval */
1456 		       + sizeof(u_int16_t) /* capinfo */
1457 		       + 2 + IEEE80211_NWID_LEN /* ssid */
1458 		       + 2 + IEEE80211_RATE_SIZE /* rates */
1459 		       + 7 /* max(7,3) */
1460 		       + 6 /* ibss (XXX could be 4?) */
1461 		       + 3 /* erp */
1462 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1463 		       /* XXX !WPA1+WPA2 fits w/o a cluster */
1464 		       + (has_wpa ? (2 * sizeof(struct ieee80211_ie_wpa)) : 0)
1465 		       + sizeof(struct ieee80211_wme_param)
1466 		);
1467 		if (m == NULL)
1468 			senderr(ENOMEM, is_tx_nobuf);
1469 
1470 		/* timestamp (should be filled later) */
1471 		memset(frm, 0, 8);
1472 		frm += 8;
1473 
1474 		/* interval */
1475 		*(u_int16_t *)frm = htole16(ic->ic_bss->ni_intval);
1476 		frm += 2;
1477 
1478 		/* capinfo */
1479 		if (ic->ic_opmode == IEEE80211_M_IBSS)
1480 			capinfo = IEEE80211_CAPINFO_IBSS;
1481 		else
1482 			capinfo = IEEE80211_CAPINFO_ESS;
1483 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1484 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1485 		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1486 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1487 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1488 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
1489 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1490 		*(u_int16_t *)frm = htole16(capinfo);
1491 		frm += 2;
1492 
1493 		/* ssid */
1494 		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
1495 		    ic->ic_bss->ni_esslen);
1496 
1497 		/* rates */
1498 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1499 
1500 		/* variable */
1501 		if (ic->ic_phytype == IEEE80211_T_FH) {
1502 			*frm++ = IEEE80211_ELEMID_FHPARMS;
1503 			*frm++ = 5;
1504 			*frm++ = ni->ni_fhdwell & 0x00ff;
1505 			*frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1506 			*frm++ = IEEE80211_FH_CHANSET(
1507 			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1508 			*frm++ = IEEE80211_FH_CHANPAT(
1509 			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1510 			*frm++ = ni->ni_fhindex;
1511 		} else {
1512 			*frm++ = IEEE80211_ELEMID_DSPARMS;
1513 			*frm++ = 1;
1514 			*frm++ = ieee80211_chan2ieee(ic, ic->ic_curchan);
1515 		}
1516 
1517 		/* ibss */
1518 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
1519 			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1520 			*frm++ = 2;
1521 			*frm++ = 0; *frm++ = 0;	/* TODO: ATIM window */
1522 		}
1523 
1524 		/* wpa */
1525 		if (has_wpa)
1526 			frm = ieee80211_add_wpa(frm, ic);
1527 
1528 		/* erp */
1529 		if (ic->ic_curmode == IEEE80211_MODE_11G)
1530 			frm = ieee80211_add_erp(frm, ic);
1531 
1532 		/* xrates */
1533 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1534 
1535 		/* wme */
1536 		if (ic->ic_flags & IEEE80211_F_WME)
1537 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1538 
1539 		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1540 		break;
1541 	}
1542 
1543 	case IEEE80211_FC0_SUBTYPE_AUTH: {
1544 		status = arg >> 16;
1545 		arg &= 0xffff;
1546 		const bool has_challenge =
1547 		    (arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1548 		     arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1549 		    ni->ni_challenge != NULL;
1550 
1551 		/*
1552 		 * Deduce whether we're doing open authentication or
1553 		 * shared key authentication.  We do the latter if
1554 		 * we're in the middle of a shared key authentication
1555 		 * handshake or if we're initiating an authentication
1556 		 * request and configured to use shared key.
1557 		 */
1558 		const bool is_shared_key = has_challenge ||
1559 		    (arg >= IEEE80211_AUTH_SHARED_RESPONSE) ||
1560 		    (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1561 		     ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1562 
1563 		const bool need_challenge =
1564 		    has_challenge && (status == IEEE80211_STATUS_SUCCESS);
1565 
1566 		const int frm_size = 3 * sizeof(u_int16_t)
1567 			+ (need_challenge ?
1568 				sizeof(u_int16_t)+IEEE80211_CHALLENGE_LEN : 0);
1569 
1570 		m = ieee80211_getmgtframe(&frm, frm_size);
1571 		if (m == NULL)
1572 			senderr(ENOMEM, is_tx_nobuf);
1573 
1574 		((u_int16_t *)frm)[0] =
1575 		      is_shared_key ? htole16(IEEE80211_AUTH_ALG_SHARED)
1576 		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1577 		((u_int16_t *)frm)[1] = htole16(arg);	/* sequence number */
1578 		((u_int16_t *)frm)[2] = htole16(status);/* status */
1579 
1580 		if (need_challenge) {
1581 			((u_int16_t *)frm)[3] =
1582 			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1583 			    IEEE80211_ELEMID_CHALLENGE);
1584 			memcpy(&((u_int16_t *)frm)[4], ni->ni_challenge,
1585 			    IEEE80211_CHALLENGE_LEN);
1586 
1587 			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1588 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1589 				    "[%s] request encrypt frame (%s)\n",
1590 				    ether_sprintf(ni->ni_macaddr), __func__);
1591 				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1592 			}
1593 		}
1594 
1595 		m->m_pkthdr.len = m->m_len = frm_size;
1596 
1597 		/* XXX not right for shared key */
1598 		if (status == IEEE80211_STATUS_SUCCESS)
1599 			IEEE80211_NODE_STAT(ni, tx_auth);
1600 		else
1601 			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1602 
1603 		if (ic->ic_opmode == IEEE80211_M_STA)
1604 			timer = IEEE80211_TRANS_WAIT;
1605 		break;
1606 	}
1607 
1608 	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1609 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1610 			"[%s] send station deauthenticate (reason %d)\n",
1611 			ether_sprintf(ni->ni_macaddr), arg);
1612 		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1613 		if (m == NULL)
1614 			senderr(ENOMEM, is_tx_nobuf);
1615 		*(u_int16_t *)frm = htole16(arg);	/* reason */
1616 		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1617 
1618 		IEEE80211_NODE_STAT(ni, tx_deauth);
1619 		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1620 
1621 		ieee80211_node_unauthorize(ni);		/* port closed */
1622 		break;
1623 
1624 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1625 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1626 		/*
1627 		 * asreq frame format
1628 		 *	[2] capability information
1629 		 *	[2] listen interval
1630 		 *	[6*] current AP address (reassoc only)
1631 		 *	[tlv] ssid
1632 		 *	[tlv] supported rates
1633 		 *	[tlv] extended supported rates
1634 		 *	[tlv] WME
1635 		 *	[tlv] user-specified ie's
1636 		 */
1637 		m = ieee80211_getmgtframe(&frm,
1638 			 sizeof(u_int16_t)
1639 		       + sizeof(u_int16_t)
1640 		       + IEEE80211_ADDR_LEN
1641 		       + 2 + IEEE80211_NWID_LEN
1642 		       + 2 + IEEE80211_RATE_SIZE
1643 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1644 		       + sizeof(struct ieee80211_wme_info)
1645 		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1646 		);
1647 		if (m == NULL)
1648 			senderr(ENOMEM, is_tx_nobuf);
1649 
1650 		capinfo = 0;
1651 		if (ic->ic_opmode == IEEE80211_M_IBSS)
1652 			capinfo |= IEEE80211_CAPINFO_IBSS;
1653 		else /* IEEE80211_M_STA */
1654 			capinfo |= IEEE80211_CAPINFO_ESS;
1655 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1656 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1657 		/*
1658 		 * NB: Some 11a AP's reject the request when
1659 		 *     short premable is set.
1660 		 */
1661 		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1662 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1663 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1664 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) &&
1665 		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1666 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1667 		*(u_int16_t *)frm = htole16(capinfo);
1668 		frm += 2;
1669 
1670 		*(u_int16_t *)frm = htole16(ic->ic_lintval);
1671 		frm += 2;
1672 
1673 		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1674 			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1675 			frm += IEEE80211_ADDR_LEN;
1676 		}
1677 
1678 		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1679 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1680 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1681 		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1682 			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1683 		if (ic->ic_opt_ie != NULL) {
1684 			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1685 			frm += ic->ic_opt_ie_len;
1686 		}
1687 		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1688 
1689 		timer = IEEE80211_TRANS_WAIT;
1690 		break;
1691 
1692 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1693 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1694 		/*
1695 		 * asreq frame format
1696 		 *	[2] capability information
1697 		 *	[2] status
1698 		 *	[2] association ID
1699 		 *	[tlv] supported rates
1700 		 *	[tlv] extended supported rates
1701 		 *	[tlv] WME (if enabled and STA enabled)
1702 		 */
1703 		m = ieee80211_getmgtframe(&frm,
1704 			 sizeof(u_int16_t)
1705 		       + sizeof(u_int16_t)
1706 		       + sizeof(u_int16_t)
1707 		       + 2 + IEEE80211_RATE_SIZE
1708 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1709 		       + sizeof(struct ieee80211_wme_param)
1710 		);
1711 		if (m == NULL)
1712 			senderr(ENOMEM, is_tx_nobuf);
1713 
1714 		capinfo = IEEE80211_CAPINFO_ESS;
1715 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1716 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1717 		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1718 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1719 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1720 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
1721 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1722 		*(u_int16_t *)frm = htole16(capinfo);
1723 		frm += 2;
1724 
1725 		*(u_int16_t *)frm = htole16(arg);	/* status */
1726 		frm += 2;
1727 
1728 		if (arg == IEEE80211_STATUS_SUCCESS) {
1729 			*(u_int16_t *)frm = htole16(ni->ni_associd);
1730 			IEEE80211_NODE_STAT(ni, tx_assoc);
1731 		} else {
1732 			*(u_int16_t *)frm = 0;
1733 			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1734 		}
1735 		frm += 2;
1736 
1737 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1738 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1739 		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1740 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1741 		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1742 		break;
1743 
1744 	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1745 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1746 			"[%s] send station disassociate (reason %d)\n",
1747 			ether_sprintf(ni->ni_macaddr), arg);
1748 		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1749 		if (m == NULL)
1750 			senderr(ENOMEM, is_tx_nobuf);
1751 		*(u_int16_t *)frm = htole16(arg);	/* reason */
1752 		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1753 
1754 		IEEE80211_NODE_STAT(ni, tx_disassoc);
1755 		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1756 		break;
1757 
1758 	default:
1759 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1760 			"[%s] invalid mgmt frame type %u\n",
1761 			ether_sprintf(ni->ni_macaddr), type);
1762 		senderr(EINVAL, is_tx_unknownmgt);
1763 		/* NOTREACHED */
1764 	}
1765 	ret = ieee80211_mgmt_output(ic, ni, m, type, timer);
1766 	if (ret != 0) {
1767 bad:
1768 		ieee80211_free_node(ni);
1769 	}
1770 	return ret;
1771 #undef senderr
1772 }
1773 
1774 /*
1775  * Build a RTS (Request To Send) control frame.
1776  */
1777 struct mbuf *
ieee80211_get_rts(struct ieee80211com * ic,const struct ieee80211_frame * wh,uint16_t dur)1778 ieee80211_get_rts(struct ieee80211com *ic, const struct ieee80211_frame *wh,
1779     uint16_t dur)
1780 {
1781 	struct ieee80211_frame_rts *rts;
1782 	struct mbuf *m;
1783 
1784 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1785 	if (m == NULL)
1786 		return NULL;
1787 
1788 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
1789 
1790 	rts = mtod(m, struct ieee80211_frame_rts *);
1791 	rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1792 	    IEEE80211_FC0_SUBTYPE_RTS;
1793 	rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1794 	*(uint16_t *)rts->i_dur = htole16(dur);
1795 	IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1796 	IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1797 
1798 	return m;
1799 }
1800 
1801 /*
1802  * Build a CTS-to-self (Clear To Send) control frame.
1803  */
1804 struct mbuf *
ieee80211_get_cts_to_self(struct ieee80211com * ic,uint16_t dur)1805 ieee80211_get_cts_to_self(struct ieee80211com *ic, uint16_t dur)
1806 {
1807 	struct ieee80211_frame_cts *cts;
1808 	struct mbuf *m;
1809 
1810 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1811 	if (m == NULL)
1812 		return NULL;
1813 
1814 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts);
1815 
1816 	cts = mtod(m, struct ieee80211_frame_cts *);
1817 	cts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1818 	    IEEE80211_FC0_SUBTYPE_CTS;
1819 	cts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1820 	*(uint16_t *)cts->i_dur = htole16(dur);
1821 	IEEE80211_ADDR_COPY(cts->i_ra, ic->ic_myaddr);
1822 
1823 	return m;
1824 }
1825 
1826 /*
1827  * Allocate a beacon frame and fill in the appropriate bits.
1828  */
1829 struct mbuf *
ieee80211_beacon_alloc(struct ieee80211com * ic,struct ieee80211_node * ni,struct ieee80211_beacon_offsets * bo)1830 ieee80211_beacon_alloc(struct ieee80211com *ic, struct ieee80211_node *ni,
1831 	struct ieee80211_beacon_offsets *bo)
1832 {
1833 	struct ifnet *ifp = ic->ic_ifp;
1834 	struct ieee80211_frame *wh;
1835 	struct mbuf *m;
1836 	int pktlen;
1837 	u_int8_t *frm, *efrm;
1838 	u_int16_t capinfo;
1839 	struct ieee80211_rateset *rs;
1840 
1841 	rs = &ni->ni_rates;
1842 
1843 	/*
1844 	 * beacon frame format
1845 	 *	[8] time stamp
1846 	 *	[2] beacon interval
1847 	 *	[2] cabability information
1848 	 *	[tlv] ssid
1849 	 *	[tlv] supported rates
1850 	 *	[3] parameter set (DS)
1851 	 *	[tlv] parameter set (IBSS/TIM)
1852 	 *	[tlv] extended rate phy (ERP)
1853 	 *	[tlv] extended supported rates
1854 	 *	[tlv] WME parameters
1855 	 *	[tlv] WPA/RSN parameters
1856 	 * XXX Vendor-specific OIDs (e.g. Atheros)
1857 	 *
1858 	 * NB: we allocate the max space required for the TIM bitmap
1859 	 * (ic_tim_len).
1860 	 */
1861 	pktlen =   8					/* time stamp */
1862 		 + sizeof(u_int16_t)			/* beacon interval */
1863 		 + sizeof(u_int16_t)			/* capabilities */
1864 		 + 2 + ni->ni_esslen			/* ssid */
1865 		 + 2 + IEEE80211_RATE_SIZE		/* supported rates */
1866 		 + 2 + 1				/* DS parameters */
1867 		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
1868 		 + 2 + 1				/* ERP */
1869 		 + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1870 		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
1871 			sizeof(struct ieee80211_wme_param) : 0)
1872 		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
1873 			2*sizeof(struct ieee80211_ie_wpa) : 0)
1874 		 ;
1875 	m = ieee80211_getmgtframe(&frm, pktlen);
1876 	if (m == NULL) {
1877 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1878 			"%s: cannot get buf; size %u\n", __func__, pktlen);
1879 		ic->ic_stats.is_tx_nobuf++;
1880 		return NULL;
1881 	}
1882 
1883 	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
1884 	frm += 8;
1885 
1886 	*(u_int16_t *)frm = htole16(ni->ni_intval);
1887 	frm += 2;
1888 
1889 	if (ic->ic_opmode == IEEE80211_M_IBSS)
1890 		capinfo = IEEE80211_CAPINFO_IBSS;
1891 	else
1892 		capinfo = IEEE80211_CAPINFO_ESS;
1893 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1894 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1895 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1896 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1897 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1898 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1899 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1900 	bo->bo_caps = (u_int16_t *)frm;
1901 	*(u_int16_t *)frm = htole16(capinfo);
1902 	frm += 2;
1903 
1904 	*frm++ = IEEE80211_ELEMID_SSID;
1905 	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
1906 		*frm++ = ni->ni_esslen;
1907 		memcpy(frm, ni->ni_essid, ni->ni_esslen);
1908 		frm += ni->ni_esslen;
1909 	} else
1910 		*frm++ = 0;
1911 
1912 	frm = ieee80211_add_rates(frm, rs);
1913 
1914 	if (ic->ic_curmode != IEEE80211_MODE_FH) {
1915 		*frm++ = IEEE80211_ELEMID_DSPARMS;
1916 		*frm++ = 1;
1917 		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1918 	}
1919 
1920 	bo->bo_tim = frm;
1921 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1922 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1923 		*frm++ = 2;
1924 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1925 		bo->bo_tim_len = 0;
1926 	} else {
1927 		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *)frm;
1928 
1929 		tie->tim_ie = IEEE80211_ELEMID_TIM;
1930 		tie->tim_len = 4;	/* length */
1931 		tie->tim_count = 0;	/* DTIM count */
1932 		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
1933 		tie->tim_bitctl = 0;	/* bitmap control */
1934 		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
1935 		frm += sizeof(struct ieee80211_tim_ie);
1936 		bo->bo_tim_len = 1;
1937 	}
1938 
1939 	bo->bo_trailer = frm;
1940 	if (ic->ic_flags & IEEE80211_F_WME) {
1941 		bo->bo_wme = frm;
1942 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1943 		ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1944 	}
1945 
1946 	if (ic->ic_flags & IEEE80211_F_WPA)
1947 		frm = ieee80211_add_wpa(frm, ic);
1948 
1949 	if (ic->ic_curmode == IEEE80211_MODE_11G)
1950 		frm = ieee80211_add_erp(frm, ic);
1951 
1952 	efrm = ieee80211_add_xrates(frm, rs);
1953 
1954 	bo->bo_trailer_len = efrm - bo->bo_trailer;
1955 	m->m_pkthdr.len = m->m_len = efrm - mtod(m, u_int8_t *);
1956 
1957 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1958 	IASSERT(m != NULL, ("no space for 802.11 header?"));
1959 
1960 	wh = mtod(m, struct ieee80211_frame *);
1961 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1962 	    IEEE80211_FC0_SUBTYPE_BEACON;
1963 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1964 	*(u_int16_t *)wh->i_dur = 0;
1965 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
1966 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
1967 	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
1968 	*(u_int16_t *)wh->i_seq = 0;
1969 
1970 	return m;
1971 }
1972 
1973 /*
1974  * Update the dynamic parts of a beacon frame based on the current state.
1975  */
1976 int
ieee80211_beacon_update(struct ieee80211com * ic,struct ieee80211_node * ni,struct ieee80211_beacon_offsets * bo,struct mbuf * m,int mcast)1977 ieee80211_beacon_update(struct ieee80211com *ic, struct ieee80211_node *ni,
1978     struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
1979 {
1980 	int len_changed = 0;
1981 	u_int16_t capinfo;
1982 
1983 	IEEE80211_BEACON_LOCK(ic);
1984 
1985 	/* XXX faster to recalculate entirely or just changes? */
1986 	if (ic->ic_opmode == IEEE80211_M_IBSS)
1987 		capinfo = IEEE80211_CAPINFO_IBSS;
1988 	else
1989 		capinfo = IEEE80211_CAPINFO_ESS;
1990 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1991 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1992 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1993 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1994 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1995 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1996 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1997 	*bo->bo_caps = htole16(capinfo);
1998 
1999 	if (ic->ic_flags & IEEE80211_F_WME) {
2000 		struct ieee80211_wme_state *wme = &ic->ic_wme;
2001 
2002 		/*
2003 		 * Check for aggressive mode change.  When there is
2004 		 * significant high priority traffic in the BSS
2005 		 * throttle back BE traffic by using conservative
2006 		 * parameters.  Otherwise BE uses aggressive params
2007 		 * to optimize performance of legacy/non-QoS traffic.
2008 		 */
2009 		if (wme->wme_flags & WME_F_AGGRMODE) {
2010 			if (wme->wme_hipri_traffic >
2011 			    wme->wme_hipri_switch_thresh) {
2012 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
2013 				    "%s: traffic %u, disable aggressive mode\n",
2014 				    __func__, wme->wme_hipri_traffic);
2015 				wme->wme_flags &= ~WME_F_AGGRMODE;
2016 				ieee80211_wme_updateparams_locked(ic);
2017 				wme->wme_hipri_traffic =
2018 					wme->wme_hipri_switch_hysteresis;
2019 			} else
2020 				wme->wme_hipri_traffic = 0;
2021 		} else {
2022 			if (wme->wme_hipri_traffic <=
2023 			    wme->wme_hipri_switch_thresh) {
2024 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
2025 				    "%s: traffic %u, enable aggressive mode\n",
2026 				    __func__, wme->wme_hipri_traffic);
2027 				wme->wme_flags |= WME_F_AGGRMODE;
2028 				ieee80211_wme_updateparams_locked(ic);
2029 				wme->wme_hipri_traffic = 0;
2030 			} else
2031 				wme->wme_hipri_traffic =
2032 					wme->wme_hipri_switch_hysteresis;
2033 		}
2034 		if (ic->ic_flags & IEEE80211_F_WMEUPDATE) {
2035 			(void)ieee80211_add_wme_param(bo->bo_wme, wme);
2036 			ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
2037 		}
2038 	}
2039 
2040 #ifndef IEEE80211_NO_HOSTAP
2041 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
2042 		struct ieee80211_tim_ie *tie =
2043 			(struct ieee80211_tim_ie *)bo->bo_tim;
2044 		if (ic->ic_flags & IEEE80211_F_TIMUPDATE) {
2045 			u_int timlen, timoff, i;
2046 			/*
2047 			 * ATIM/DTIM needs updating.  If it fits in the
2048 			 * current space allocated then just copy in the
2049 			 * new bits.  Otherwise we need to move any trailing
2050 			 * data to make room.  Note that we know there is
2051 			 * contiguous space because ieee80211_beacon_allocate
2052 			 * insures there is space in the mbuf to write a
2053 			 * maximal-size virtual bitmap (based on ic_max_aid).
2054 			 */
2055 			/*
2056 			 * Calculate the bitmap size and offset, copy any
2057 			 * trailer out of the way, and then copy in the
2058 			 * new bitmap and update the information element.
2059 			 * Note that the tim bitmap must contain at least
2060 			 * one byte and any offset must be even.
2061 			 */
2062 			if (ic->ic_ps_pending != 0) {
2063 				timoff = 128;		/* impossibly large */
2064 				for (i = 0; i < ic->ic_tim_len; i++)
2065 					if (ic->ic_tim_bitmap[i]) {
2066 						timoff = i &~ 1;
2067 						break;
2068 					}
2069 				IASSERT(timoff != 128, ("tim bitmap empty!"));
2070 				for (i = ic->ic_tim_len-1; i >= timoff; i--)
2071 					if (ic->ic_tim_bitmap[i])
2072 						break;
2073 				timlen = 1 + (i - timoff);
2074 			} else {
2075 				timoff = 0;
2076 				timlen = 1;
2077 			}
2078 			if (timlen != bo->bo_tim_len) {
2079 				/* copy up/down trailer */
2080 				memmove(tie->tim_bitmap+timlen, bo->bo_trailer,
2081 					bo->bo_trailer_len);
2082 				bo->bo_trailer = tie->tim_bitmap+timlen;
2083 				bo->bo_wme = bo->bo_trailer;
2084 				bo->bo_tim_len = timlen;
2085 
2086 				/* update information element */
2087 				tie->tim_len = 3 + timlen;
2088 				tie->tim_bitctl = timoff;
2089 				len_changed = 1;
2090 			}
2091 			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
2092 				bo->bo_tim_len);
2093 
2094 			ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
2095 
2096 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2097 				"%s: TIM updated, pending %u, off %u, len %u\n",
2098 				__func__, ic->ic_ps_pending, timoff, timlen);
2099 		}
2100 		/* count down DTIM period */
2101 		if (tie->tim_count == 0)
2102 			tie->tim_count = tie->tim_period - 1;
2103 		else
2104 			tie->tim_count--;
2105 		/* update state for buffered multicast frames on DTIM */
2106 		if (mcast && (tie->tim_count == 1 || tie->tim_period == 1))
2107 			tie->tim_bitctl |= 1;
2108 		else
2109 			tie->tim_bitctl &= ~1;
2110 	}
2111 #endif /* !IEEE80211_NO_HOSTAP */
2112 
2113 	IEEE80211_BEACON_UNLOCK(ic);
2114 
2115 	return len_changed;
2116 }
2117 
2118 /*
2119  * Save an outbound packet for a node in power-save sleep state.
2120  * The new packet is placed on the node's saved queue, and the TIM
2121  * is changed, if necessary.
2122  */
2123 void
ieee80211_pwrsave(struct ieee80211com * ic,struct ieee80211_node * ni,struct mbuf * m)2124 ieee80211_pwrsave(struct ieee80211com *ic, struct ieee80211_node *ni,
2125     struct mbuf *m)
2126 {
2127 	int qlen, age;
2128 
2129 	IEEE80211_NODE_SAVEQ_LOCK(ni);
2130 	if (IF_QFULL(&ni->ni_savedq)) {
2131 		IF_DROP(&ni->ni_savedq);
2132 		IEEE80211_NODE_SAVEQ_UNLOCK(ni);
2133 
2134 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2135 		    "[%s] pwr save q overflow, drops %" PRIu64
2136 		    " (size %d)\n",
2137 		    ether_sprintf(ni->ni_macaddr),
2138 		    ni->ni_savedq.ifq_drops, IEEE80211_PS_MAX_QUEUE);
2139 #ifdef IEEE80211_DEBUG
2140 		if (ieee80211_msg_dumppkts(ic))
2141 			ieee80211_dump_pkt(mtod(m, void *), m->m_len, -1, -1);
2142 #endif
2143 
2144 		m_freem(m);
2145 		return;
2146 	}
2147 
2148 	/*
2149 	 * Tag the frame with its expiry time and insert
2150 	 * it in the queue.  The aging interval is 4 times
2151 	 * the listen interval specified by the station.
2152 	 * Frames that sit around too long are reclaimed
2153 	 * using this information.
2154 	 */
2155 	/* XXX handle overflow? */
2156 	age = ((ni->ni_intval * ic->ic_bintval) << 2) / 1024; /* TU -> secs */
2157 	_IEEE80211_NODE_SAVEQ_ENQUEUE(ni, m, qlen, age);
2158 	IEEE80211_NODE_SAVEQ_UNLOCK(ni);
2159 
2160 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2161 		"[%s] save frame with age %d, %u now queued\n",
2162 		ether_sprintf(ni->ni_macaddr), age, qlen);
2163 
2164 	if (qlen == 1)
2165 		ic->ic_set_tim(ni, 1);
2166 }
2167