ifieee80211.c revision 229778
1/*
2 * Copyright 2001 The Aerospace Corporation.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 * 3. The name of The Aerospace Corporation may not be used to endorse or
13 *    promote products derived from this software.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AEROSPACE CORPORATION ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AEROSPACE CORPORATION BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 *
27 * $FreeBSD: head/sbin/ifconfig/ifieee80211.c 229778 2012-01-07 16:09:33Z uqs $
28 */
29
30/*-
31 * Copyright (c) 1997, 1998, 2000 The NetBSD Foundation, Inc.
32 * All rights reserved.
33 *
34 * This code is derived from software contributed to The NetBSD Foundation
35 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
36 * NASA Ames Research Center.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 *    notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 *    notice, this list of conditions and the following disclaimer in the
45 *    documentation and/or other materials provided with the distribution.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
48 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
49 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
50 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
51 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
52 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
53 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
54 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
55 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
56 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
57 * POSSIBILITY OF SUCH DAMAGE.
58 */
59
60#include <sys/param.h>
61#include <sys/ioctl.h>
62#include <sys/socket.h>
63#include <sys/sysctl.h>
64#include <sys/time.h>
65
66#include <net/ethernet.h>
67#include <net/if.h>
68#include <net/if_dl.h>
69#include <net/if_types.h>
70#include <net/if_media.h>
71#include <net/route.h>
72
73#include <net80211/ieee80211_ioctl.h>
74#include <net80211/ieee80211_freebsd.h>
75#include <net80211/ieee80211_superg.h>
76#include <net80211/ieee80211_tdma.h>
77#include <net80211/ieee80211_mesh.h>
78
79#include <assert.h>
80#include <ctype.h>
81#include <err.h>
82#include <errno.h>
83#include <fcntl.h>
84#include <inttypes.h>
85#include <stdio.h>
86#include <stdlib.h>
87#include <string.h>
88#include <unistd.h>
89#include <stdarg.h>
90#include <stddef.h>		/* NB: for offsetof */
91
92#include "ifconfig.h"
93#include "regdomain.h"
94
95#ifndef IEEE80211_FIXED_RATE_NONE
96#define	IEEE80211_FIXED_RATE_NONE	0xff
97#endif
98
99/* XXX need these publicly defined or similar */
100#ifndef IEEE80211_NODE_AUTH
101#define	IEEE80211_NODE_AUTH	0x000001	/* authorized for data */
102#define	IEEE80211_NODE_QOS	0x000002	/* QoS enabled */
103#define	IEEE80211_NODE_ERP	0x000004	/* ERP enabled */
104#define	IEEE80211_NODE_PWR_MGT	0x000010	/* power save mode enabled */
105#define	IEEE80211_NODE_AREF	0x000020	/* authentication ref held */
106#define	IEEE80211_NODE_HT	0x000040	/* HT enabled */
107#define	IEEE80211_NODE_HTCOMPAT	0x000080	/* HT setup w/ vendor OUI's */
108#define	IEEE80211_NODE_WPS	0x000100	/* WPS association */
109#define	IEEE80211_NODE_TSN	0x000200	/* TSN association */
110#define	IEEE80211_NODE_AMPDU_RX	0x000400	/* AMPDU rx enabled */
111#define	IEEE80211_NODE_AMPDU_TX	0x000800	/* AMPDU tx enabled */
112#define	IEEE80211_NODE_MIMO_PS	0x001000	/* MIMO power save enabled */
113#define	IEEE80211_NODE_MIMO_RTS	0x002000	/* send RTS in MIMO PS */
114#define	IEEE80211_NODE_RIFS	0x004000	/* RIFS enabled */
115#define	IEEE80211_NODE_SGI20	0x008000	/* Short GI in HT20 enabled */
116#define	IEEE80211_NODE_SGI40	0x010000	/* Short GI in HT40 enabled */
117#define	IEEE80211_NODE_ASSOCID	0x020000	/* xmit requires associd */
118#define	IEEE80211_NODE_AMSDU_RX	0x040000	/* AMSDU rx enabled */
119#define	IEEE80211_NODE_AMSDU_TX	0x080000	/* AMSDU tx enabled */
120#endif
121
122#define	MAXCHAN	1536		/* max 1.5K channels */
123
124#define	MAXCOL	78
125static	int col;
126static	char spacer;
127
128static void LINE_INIT(char c);
129static void LINE_BREAK(void);
130static void LINE_CHECK(const char *fmt, ...);
131
132static const char *modename[IEEE80211_MODE_MAX] = {
133	[IEEE80211_MODE_AUTO]	  = "auto",
134	[IEEE80211_MODE_11A]	  = "11a",
135	[IEEE80211_MODE_11B]	  = "11b",
136	[IEEE80211_MODE_11G]	  = "11g",
137	[IEEE80211_MODE_FH]	  = "fh",
138	[IEEE80211_MODE_TURBO_A]  = "turboA",
139	[IEEE80211_MODE_TURBO_G]  = "turboG",
140	[IEEE80211_MODE_STURBO_A] = "sturbo",
141	[IEEE80211_MODE_11NA]	  = "11na",
142	[IEEE80211_MODE_11NG]	  = "11ng",
143	[IEEE80211_MODE_HALF]	  = "half",
144	[IEEE80211_MODE_QUARTER]  = "quarter"
145};
146
147static void set80211(int s, int type, int val, int len, void *data);
148static int get80211(int s, int type, void *data, int len);
149static int get80211len(int s, int type, void *data, int len, int *plen);
150static int get80211val(int s, int type, int *val);
151static const char *get_string(const char *val, const char *sep,
152    u_int8_t *buf, int *lenp);
153static void print_string(const u_int8_t *buf, int len);
154static void print_regdomain(const struct ieee80211_regdomain *, int);
155static void print_channels(int, const struct ieee80211req_chaninfo *,
156    int allchans, int verbose);
157static void regdomain_makechannels(struct ieee80211_regdomain_req *,
158    const struct ieee80211_devcaps_req *);
159static const char *mesh_linkstate_string(uint8_t state);
160
161static struct ieee80211req_chaninfo *chaninfo;
162static struct ieee80211_regdomain regdomain;
163static int gotregdomain = 0;
164static struct ieee80211_roamparams_req roamparams;
165static int gotroam = 0;
166static struct ieee80211_txparams_req txparams;
167static int gottxparams = 0;
168static struct ieee80211_channel curchan;
169static int gotcurchan = 0;
170static struct ifmediareq *ifmr;
171static int htconf = 0;
172static	int gothtconf = 0;
173
174static void
175gethtconf(int s)
176{
177	if (gothtconf)
178		return;
179	if (get80211val(s, IEEE80211_IOC_HTCONF, &htconf) < 0)
180		warn("unable to get HT configuration information");
181	gothtconf = 1;
182}
183
184/*
185 * Collect channel info from the kernel.  We use this (mostly)
186 * to handle mapping between frequency and IEEE channel number.
187 */
188static void
189getchaninfo(int s)
190{
191	if (chaninfo != NULL)
192		return;
193	chaninfo = malloc(IEEE80211_CHANINFO_SIZE(MAXCHAN));
194	if (chaninfo == NULL)
195		errx(1, "no space for channel list");
196	if (get80211(s, IEEE80211_IOC_CHANINFO, chaninfo,
197	    IEEE80211_CHANINFO_SIZE(MAXCHAN)) < 0)
198		err(1, "unable to get channel information");
199	ifmr = ifmedia_getstate(s);
200	gethtconf(s);
201}
202
203static struct regdata *
204getregdata(void)
205{
206	static struct regdata *rdp = NULL;
207	if (rdp == NULL) {
208		rdp = lib80211_alloc_regdata();
209		if (rdp == NULL)
210			errx(-1, "missing or corrupted regdomain database");
211	}
212	return rdp;
213}
214
215/*
216 * Given the channel at index i with attributes from,
217 * check if there is a channel with attributes to in
218 * the channel table.  With suitable attributes this
219 * allows the caller to look for promotion; e.g. from
220 * 11b > 11g.
221 */
222static int
223canpromote(int i, int from, int to)
224{
225	const struct ieee80211_channel *fc = &chaninfo->ic_chans[i];
226	int j;
227
228	if ((fc->ic_flags & from) != from)
229		return i;
230	/* NB: quick check exploiting ordering of chans w/ same frequency */
231	if (i+1 < chaninfo->ic_nchans &&
232	    chaninfo->ic_chans[i+1].ic_freq == fc->ic_freq &&
233	    (chaninfo->ic_chans[i+1].ic_flags & to) == to)
234		return i+1;
235	/* brute force search in case channel list is not ordered */
236	for (j = 0; j < chaninfo->ic_nchans; j++) {
237		const struct ieee80211_channel *tc = &chaninfo->ic_chans[j];
238		if (j != i &&
239		    tc->ic_freq == fc->ic_freq && (tc->ic_flags & to) == to)
240		return j;
241	}
242	return i;
243}
244
245/*
246 * Handle channel promotion.  When a channel is specified with
247 * only a frequency we want to promote it to the ``best'' channel
248 * available.  The channel list has separate entries for 11b, 11g,
249 * 11a, and 11n[ga] channels so specifying a frequency w/o any
250 * attributes requires we upgrade, e.g. from 11b -> 11g.  This
251 * gets complicated when the channel is specified on the same
252 * command line with a media request that constrains the available
253 * channe list (e.g. mode 11a); we want to honor that to avoid
254 * confusing behaviour.
255 */
256static int
257promote(int i)
258{
259	/*
260	 * Query the current mode of the interface in case it's
261	 * constrained (e.g. to 11a).  We must do this carefully
262	 * as there may be a pending ifmedia request in which case
263	 * asking the kernel will give us the wrong answer.  This
264	 * is an unfortunate side-effect of the way ifconfig is
265	 * structure for modularity (yech).
266	 *
267	 * NB: ifmr is actually setup in getchaninfo (above); we
268	 *     assume it's called coincident with to this call so
269	 *     we have a ``current setting''; otherwise we must pass
270	 *     the socket descriptor down to here so we can make
271	 *     the ifmedia_getstate call ourselves.
272	 */
273	int chanmode = ifmr != NULL ? IFM_MODE(ifmr->ifm_current) : IFM_AUTO;
274
275	/* when ambiguous promote to ``best'' */
276	/* NB: we abitrarily pick HT40+ over HT40- */
277	if (chanmode != IFM_IEEE80211_11B)
278		i = canpromote(i, IEEE80211_CHAN_B, IEEE80211_CHAN_G);
279	if (chanmode != IFM_IEEE80211_11G && (htconf & 1)) {
280		i = canpromote(i, IEEE80211_CHAN_G,
281			IEEE80211_CHAN_G | IEEE80211_CHAN_HT20);
282		if (htconf & 2) {
283			i = canpromote(i, IEEE80211_CHAN_G,
284				IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D);
285			i = canpromote(i, IEEE80211_CHAN_G,
286				IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U);
287		}
288	}
289	if (chanmode != IFM_IEEE80211_11A && (htconf & 1)) {
290		i = canpromote(i, IEEE80211_CHAN_A,
291			IEEE80211_CHAN_A | IEEE80211_CHAN_HT20);
292		if (htconf & 2) {
293			i = canpromote(i, IEEE80211_CHAN_A,
294				IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D);
295			i = canpromote(i, IEEE80211_CHAN_A,
296				IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U);
297		}
298	}
299	return i;
300}
301
302static void
303mapfreq(struct ieee80211_channel *chan, int freq, int flags)
304{
305	int i;
306
307	for (i = 0; i < chaninfo->ic_nchans; i++) {
308		const struct ieee80211_channel *c = &chaninfo->ic_chans[i];
309
310		if (c->ic_freq == freq && (c->ic_flags & flags) == flags) {
311			if (flags == 0) {
312				/* when ambiguous promote to ``best'' */
313				c = &chaninfo->ic_chans[promote(i)];
314			}
315			*chan = *c;
316			return;
317		}
318	}
319	errx(1, "unknown/undefined frequency %u/0x%x", freq, flags);
320}
321
322static void
323mapchan(struct ieee80211_channel *chan, int ieee, int flags)
324{
325	int i;
326
327	for (i = 0; i < chaninfo->ic_nchans; i++) {
328		const struct ieee80211_channel *c = &chaninfo->ic_chans[i];
329
330		if (c->ic_ieee == ieee && (c->ic_flags & flags) == flags) {
331			if (flags == 0) {
332				/* when ambiguous promote to ``best'' */
333				c = &chaninfo->ic_chans[promote(i)];
334			}
335			*chan = *c;
336			return;
337		}
338	}
339	errx(1, "unknown/undefined channel number %d flags 0x%x", ieee, flags);
340}
341
342static const struct ieee80211_channel *
343getcurchan(int s)
344{
345	if (gotcurchan)
346		return &curchan;
347	if (get80211(s, IEEE80211_IOC_CURCHAN, &curchan, sizeof(curchan)) < 0) {
348		int val;
349		/* fall back to legacy ioctl */
350		if (get80211val(s, IEEE80211_IOC_CHANNEL, &val) < 0)
351			err(-1, "cannot figure out current channel");
352		getchaninfo(s);
353		mapchan(&curchan, val, 0);
354	}
355	gotcurchan = 1;
356	return &curchan;
357}
358
359static enum ieee80211_phymode
360chan2mode(const struct ieee80211_channel *c)
361{
362	if (IEEE80211_IS_CHAN_HTA(c))
363		return IEEE80211_MODE_11NA;
364	if (IEEE80211_IS_CHAN_HTG(c))
365		return IEEE80211_MODE_11NG;
366	if (IEEE80211_IS_CHAN_108A(c))
367		return IEEE80211_MODE_TURBO_A;
368	if (IEEE80211_IS_CHAN_108G(c))
369		return IEEE80211_MODE_TURBO_G;
370	if (IEEE80211_IS_CHAN_ST(c))
371		return IEEE80211_MODE_STURBO_A;
372	if (IEEE80211_IS_CHAN_FHSS(c))
373		return IEEE80211_MODE_FH;
374	if (IEEE80211_IS_CHAN_HALF(c))
375		return IEEE80211_MODE_HALF;
376	if (IEEE80211_IS_CHAN_QUARTER(c))
377		return IEEE80211_MODE_QUARTER;
378	if (IEEE80211_IS_CHAN_A(c))
379		return IEEE80211_MODE_11A;
380	if (IEEE80211_IS_CHAN_ANYG(c))
381		return IEEE80211_MODE_11G;
382	if (IEEE80211_IS_CHAN_B(c))
383		return IEEE80211_MODE_11B;
384	return IEEE80211_MODE_AUTO;
385}
386
387static void
388getroam(int s)
389{
390	if (gotroam)
391		return;
392	if (get80211(s, IEEE80211_IOC_ROAM,
393	    &roamparams, sizeof(roamparams)) < 0)
394		err(1, "unable to get roaming parameters");
395	gotroam = 1;
396}
397
398static void
399setroam_cb(int s, void *arg)
400{
401	struct ieee80211_roamparams_req *roam = arg;
402	set80211(s, IEEE80211_IOC_ROAM, 0, sizeof(*roam), roam);
403}
404
405static void
406gettxparams(int s)
407{
408	if (gottxparams)
409		return;
410	if (get80211(s, IEEE80211_IOC_TXPARAMS,
411	    &txparams, sizeof(txparams)) < 0)
412		err(1, "unable to get transmit parameters");
413	gottxparams = 1;
414}
415
416static void
417settxparams_cb(int s, void *arg)
418{
419	struct ieee80211_txparams_req *txp = arg;
420	set80211(s, IEEE80211_IOC_TXPARAMS, 0, sizeof(*txp), txp);
421}
422
423static void
424getregdomain(int s)
425{
426	if (gotregdomain)
427		return;
428	if (get80211(s, IEEE80211_IOC_REGDOMAIN,
429	    &regdomain, sizeof(regdomain)) < 0)
430		err(1, "unable to get regulatory domain info");
431	gotregdomain = 1;
432}
433
434static void
435getdevcaps(int s, struct ieee80211_devcaps_req *dc)
436{
437	if (get80211(s, IEEE80211_IOC_DEVCAPS, dc,
438	    IEEE80211_DEVCAPS_SPACE(dc)) < 0)
439		err(1, "unable to get device capabilities");
440}
441
442static void
443setregdomain_cb(int s, void *arg)
444{
445	struct ieee80211_regdomain_req *req;
446	struct ieee80211_regdomain *rd = arg;
447	struct ieee80211_devcaps_req *dc;
448	struct regdata *rdp = getregdata();
449
450	if (rd->country != NO_COUNTRY) {
451		const struct country *cc;
452		/*
453		 * Check current country seting to make sure it's
454		 * compatible with the new regdomain.  If not, then
455		 * override it with any default country for this
456		 * SKU.  If we cannot arrange a match, then abort.
457		 */
458		cc = lib80211_country_findbycc(rdp, rd->country);
459		if (cc == NULL)
460			errx(1, "unknown ISO country code %d", rd->country);
461		if (cc->rd->sku != rd->regdomain) {
462			const struct regdomain *rp;
463			/*
464			 * Check if country is incompatible with regdomain.
465			 * To enable multiple regdomains for a country code
466			 * we permit a mismatch between the regdomain and
467			 * the country's associated regdomain when the
468			 * regdomain is setup w/o a default country.  For
469			 * example, US is bound to the FCC regdomain but
470			 * we allow US to be combined with FCC3 because FCC3
471			 * has not default country.  This allows bogus
472			 * combinations like FCC3+DK which are resolved when
473			 * constructing the channel list by deferring to the
474			 * regdomain to construct the channel list.
475			 */
476			rp = lib80211_regdomain_findbysku(rdp, rd->regdomain);
477			if (rp == NULL)
478				errx(1, "country %s (%s) is not usable with "
479				    "regdomain %d", cc->isoname, cc->name,
480				    rd->regdomain);
481			else if (rp->cc != NULL && rp->cc != cc)
482				errx(1, "country %s (%s) is not usable with "
483				   "regdomain %s", cc->isoname, cc->name,
484				   rp->name);
485		}
486	}
487	/*
488	 * Fetch the device capabilities and calculate the
489	 * full set of netbands for which we request a new
490	 * channel list be constructed.  Once that's done we
491	 * push the regdomain info + channel list to the kernel.
492	 */
493	dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
494	if (dc == NULL)
495		errx(1, "no space for device capabilities");
496	dc->dc_chaninfo.ic_nchans = MAXCHAN;
497	getdevcaps(s, dc);
498#if 0
499	if (verbose) {
500		printf("drivercaps: 0x%x\n", dc->dc_drivercaps);
501		printf("cryptocaps: 0x%x\n", dc->dc_cryptocaps);
502		printf("htcaps    : 0x%x\n", dc->dc_htcaps);
503		memcpy(chaninfo, &dc->dc_chaninfo,
504		    IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
505		print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, 1/*verbose*/);
506	}
507#endif
508	req = malloc(IEEE80211_REGDOMAIN_SIZE(dc->dc_chaninfo.ic_nchans));
509	if (req == NULL)
510		errx(1, "no space for regdomain request");
511	req->rd = *rd;
512	regdomain_makechannels(req, dc);
513	if (verbose) {
514		LINE_INIT(':');
515		print_regdomain(rd, 1/*verbose*/);
516		LINE_BREAK();
517		/* blech, reallocate channel list for new data */
518		if (chaninfo != NULL)
519			free(chaninfo);
520		chaninfo = malloc(IEEE80211_CHANINFO_SPACE(&req->chaninfo));
521		if (chaninfo == NULL)
522			errx(1, "no space for channel list");
523		memcpy(chaninfo, &req->chaninfo,
524		    IEEE80211_CHANINFO_SPACE(&req->chaninfo));
525		print_channels(s, &req->chaninfo, 1/*allchans*/, 1/*verbose*/);
526	}
527	if (req->chaninfo.ic_nchans == 0)
528		errx(1, "no channels calculated");
529	set80211(s, IEEE80211_IOC_REGDOMAIN, 0,
530	    IEEE80211_REGDOMAIN_SPACE(req), req);
531	free(req);
532	free(dc);
533}
534
535static int
536ieee80211_mhz2ieee(int freq, int flags)
537{
538	struct ieee80211_channel chan;
539	mapfreq(&chan, freq, flags);
540	return chan.ic_ieee;
541}
542
543static int
544isanyarg(const char *arg)
545{
546	return (strncmp(arg, "-", 1) == 0 ||
547	    strncasecmp(arg, "any", 3) == 0 || strncasecmp(arg, "off", 3) == 0);
548}
549
550static void
551set80211ssid(const char *val, int d, int s, const struct afswtch *rafp)
552{
553	int		ssid;
554	int		len;
555	u_int8_t	data[IEEE80211_NWID_LEN];
556
557	ssid = 0;
558	len = strlen(val);
559	if (len > 2 && isdigit((int)val[0]) && val[1] == ':') {
560		ssid = atoi(val)-1;
561		val += 2;
562	}
563
564	bzero(data, sizeof(data));
565	len = sizeof(data);
566	if (get_string(val, NULL, data, &len) == NULL)
567		exit(1);
568
569	set80211(s, IEEE80211_IOC_SSID, ssid, len, data);
570}
571
572static void
573set80211meshid(const char *val, int d, int s, const struct afswtch *rafp)
574{
575	int		len;
576	u_int8_t	data[IEEE80211_NWID_LEN];
577
578	memset(data, 0, sizeof(data));
579	len = sizeof(data);
580	if (get_string(val, NULL, data, &len) == NULL)
581		exit(1);
582
583	set80211(s, IEEE80211_IOC_MESH_ID, 0, len, data);
584}
585
586static void
587set80211stationname(const char *val, int d, int s, const struct afswtch *rafp)
588{
589	int			len;
590	u_int8_t		data[33];
591
592	bzero(data, sizeof(data));
593	len = sizeof(data);
594	get_string(val, NULL, data, &len);
595
596	set80211(s, IEEE80211_IOC_STATIONNAME, 0, len, data);
597}
598
599/*
600 * Parse a channel specification for attributes/flags.
601 * The syntax is:
602 *	freq/xx		channel width (5,10,20,40,40+,40-)
603 *	freq:mode	channel mode (a,b,g,h,n,t,s,d)
604 *
605 * These can be combined in either order; e.g. 2437:ng/40.
606 * Modes are case insensitive.
607 *
608 * The result is not validated here; it's assumed to be
609 * checked against the channel table fetched from the kernel.
610 */
611static int
612getchannelflags(const char *val, int freq)
613{
614#define	_CHAN_HT	0x80000000
615	const char *cp;
616	int flags;
617
618	flags = 0;
619
620	cp = strchr(val, ':');
621	if (cp != NULL) {
622		for (cp++; isalpha((int) *cp); cp++) {
623			/* accept mixed case */
624			int c = *cp;
625			if (isupper(c))
626				c = tolower(c);
627			switch (c) {
628			case 'a':		/* 802.11a */
629				flags |= IEEE80211_CHAN_A;
630				break;
631			case 'b':		/* 802.11b */
632				flags |= IEEE80211_CHAN_B;
633				break;
634			case 'g':		/* 802.11g */
635				flags |= IEEE80211_CHAN_G;
636				break;
637			case 'h':		/* ht = 802.11n */
638			case 'n':		/* 802.11n */
639				flags |= _CHAN_HT;	/* NB: private */
640				break;
641			case 'd':		/* dt = Atheros Dynamic Turbo */
642				flags |= IEEE80211_CHAN_TURBO;
643				break;
644			case 't':		/* ht, dt, st, t */
645				/* dt and unadorned t specify Dynamic Turbo */
646				if ((flags & (IEEE80211_CHAN_STURBO|_CHAN_HT)) == 0)
647					flags |= IEEE80211_CHAN_TURBO;
648				break;
649			case 's':		/* st = Atheros Static Turbo */
650				flags |= IEEE80211_CHAN_STURBO;
651				break;
652			default:
653				errx(-1, "%s: Invalid channel attribute %c\n",
654				    val, *cp);
655			}
656		}
657	}
658	cp = strchr(val, '/');
659	if (cp != NULL) {
660		char *ep;
661		u_long cw = strtoul(cp+1, &ep, 10);
662
663		switch (cw) {
664		case 5:
665			flags |= IEEE80211_CHAN_QUARTER;
666			break;
667		case 10:
668			flags |= IEEE80211_CHAN_HALF;
669			break;
670		case 20:
671			/* NB: this may be removed below */
672			flags |= IEEE80211_CHAN_HT20;
673			break;
674		case 40:
675			if (ep != NULL && *ep == '+')
676				flags |= IEEE80211_CHAN_HT40U;
677			else if (ep != NULL && *ep == '-')
678				flags |= IEEE80211_CHAN_HT40D;
679			break;
680		default:
681			errx(-1, "%s: Invalid channel width\n", val);
682		}
683	}
684	/*
685	 * Cleanup specifications.
686	 */
687	if ((flags & _CHAN_HT) == 0) {
688		/*
689		 * If user specified freq/20 or freq/40 quietly remove
690		 * HT cw attributes depending on channel use.  To give
691		 * an explicit 20/40 width for an HT channel you must
692		 * indicate it is an HT channel since all HT channels
693		 * are also usable for legacy operation; e.g. freq:n/40.
694		 */
695		flags &= ~IEEE80211_CHAN_HT;
696	} else {
697		/*
698		 * Remove private indicator that this is an HT channel
699		 * and if no explicit channel width has been given
700		 * provide the default settings.
701		 */
702		flags &= ~_CHAN_HT;
703		if ((flags & IEEE80211_CHAN_HT) == 0) {
704			struct ieee80211_channel chan;
705			/*
706			 * Consult the channel list to see if we can use
707			 * HT40+ or HT40- (if both the map routines choose).
708			 */
709			if (freq > 255)
710				mapfreq(&chan, freq, 0);
711			else
712				mapchan(&chan, freq, 0);
713			flags |= (chan.ic_flags & IEEE80211_CHAN_HT);
714		}
715	}
716	return flags;
717#undef _CHAN_HT
718}
719
720static void
721getchannel(int s, struct ieee80211_channel *chan, const char *val)
722{
723	int v, flags;
724	char *eptr;
725
726	memset(chan, 0, sizeof(*chan));
727	if (isanyarg(val)) {
728		chan->ic_freq = IEEE80211_CHAN_ANY;
729		return;
730	}
731	getchaninfo(s);
732	errno = 0;
733	v = strtol(val, &eptr, 10);
734	if (val[0] == '\0' || val == eptr || errno == ERANGE ||
735	    /* channel may be suffixed with nothing, :flag, or /width */
736	    (eptr[0] != '\0' && eptr[0] != ':' && eptr[0] != '/'))
737		errx(1, "invalid channel specification%s",
738		    errno == ERANGE ? " (out of range)" : "");
739	flags = getchannelflags(val, v);
740	if (v > 255) {		/* treat as frequency */
741		mapfreq(chan, v, flags);
742	} else {
743		mapchan(chan, v, flags);
744	}
745}
746
747static void
748set80211channel(const char *val, int d, int s, const struct afswtch *rafp)
749{
750	struct ieee80211_channel chan;
751
752	getchannel(s, &chan, val);
753	set80211(s, IEEE80211_IOC_CURCHAN, 0, sizeof(chan), &chan);
754}
755
756static void
757set80211chanswitch(const char *val, int d, int s, const struct afswtch *rafp)
758{
759	struct ieee80211_chanswitch_req csr;
760
761	getchannel(s, &csr.csa_chan, val);
762	csr.csa_mode = 1;
763	csr.csa_count = 5;
764	set80211(s, IEEE80211_IOC_CHANSWITCH, 0, sizeof(csr), &csr);
765}
766
767static void
768set80211authmode(const char *val, int d, int s, const struct afswtch *rafp)
769{
770	int	mode;
771
772	if (strcasecmp(val, "none") == 0) {
773		mode = IEEE80211_AUTH_NONE;
774	} else if (strcasecmp(val, "open") == 0) {
775		mode = IEEE80211_AUTH_OPEN;
776	} else if (strcasecmp(val, "shared") == 0) {
777		mode = IEEE80211_AUTH_SHARED;
778	} else if (strcasecmp(val, "8021x") == 0) {
779		mode = IEEE80211_AUTH_8021X;
780	} else if (strcasecmp(val, "wpa") == 0) {
781		mode = IEEE80211_AUTH_WPA;
782	} else {
783		errx(1, "unknown authmode");
784	}
785
786	set80211(s, IEEE80211_IOC_AUTHMODE, mode, 0, NULL);
787}
788
789static void
790set80211powersavemode(const char *val, int d, int s, const struct afswtch *rafp)
791{
792	int	mode;
793
794	if (strcasecmp(val, "off") == 0) {
795		mode = IEEE80211_POWERSAVE_OFF;
796	} else if (strcasecmp(val, "on") == 0) {
797		mode = IEEE80211_POWERSAVE_ON;
798	} else if (strcasecmp(val, "cam") == 0) {
799		mode = IEEE80211_POWERSAVE_CAM;
800	} else if (strcasecmp(val, "psp") == 0) {
801		mode = IEEE80211_POWERSAVE_PSP;
802	} else if (strcasecmp(val, "psp-cam") == 0) {
803		mode = IEEE80211_POWERSAVE_PSP_CAM;
804	} else {
805		errx(1, "unknown powersavemode");
806	}
807
808	set80211(s, IEEE80211_IOC_POWERSAVE, mode, 0, NULL);
809}
810
811static void
812set80211powersave(const char *val, int d, int s, const struct afswtch *rafp)
813{
814	if (d == 0)
815		set80211(s, IEEE80211_IOC_POWERSAVE, IEEE80211_POWERSAVE_OFF,
816		    0, NULL);
817	else
818		set80211(s, IEEE80211_IOC_POWERSAVE, IEEE80211_POWERSAVE_ON,
819		    0, NULL);
820}
821
822static void
823set80211powersavesleep(const char *val, int d, int s, const struct afswtch *rafp)
824{
825	set80211(s, IEEE80211_IOC_POWERSAVESLEEP, atoi(val), 0, NULL);
826}
827
828static void
829set80211wepmode(const char *val, int d, int s, const struct afswtch *rafp)
830{
831	int	mode;
832
833	if (strcasecmp(val, "off") == 0) {
834		mode = IEEE80211_WEP_OFF;
835	} else if (strcasecmp(val, "on") == 0) {
836		mode = IEEE80211_WEP_ON;
837	} else if (strcasecmp(val, "mixed") == 0) {
838		mode = IEEE80211_WEP_MIXED;
839	} else {
840		errx(1, "unknown wep mode");
841	}
842
843	set80211(s, IEEE80211_IOC_WEP, mode, 0, NULL);
844}
845
846static void
847set80211wep(const char *val, int d, int s, const struct afswtch *rafp)
848{
849	set80211(s, IEEE80211_IOC_WEP, d, 0, NULL);
850}
851
852static int
853isundefarg(const char *arg)
854{
855	return (strcmp(arg, "-") == 0 || strncasecmp(arg, "undef", 5) == 0);
856}
857
858static void
859set80211weptxkey(const char *val, int d, int s, const struct afswtch *rafp)
860{
861	if (isundefarg(val))
862		set80211(s, IEEE80211_IOC_WEPTXKEY, IEEE80211_KEYIX_NONE, 0, NULL);
863	else
864		set80211(s, IEEE80211_IOC_WEPTXKEY, atoi(val)-1, 0, NULL);
865}
866
867static void
868set80211wepkey(const char *val, int d, int s, const struct afswtch *rafp)
869{
870	int		key = 0;
871	int		len;
872	u_int8_t	data[IEEE80211_KEYBUF_SIZE];
873
874	if (isdigit((int)val[0]) && val[1] == ':') {
875		key = atoi(val)-1;
876		val += 2;
877	}
878
879	bzero(data, sizeof(data));
880	len = sizeof(data);
881	get_string(val, NULL, data, &len);
882
883	set80211(s, IEEE80211_IOC_WEPKEY, key, len, data);
884}
885
886/*
887 * This function is purely a NetBSD compatibility interface.  The NetBSD
888 * interface is too inflexible, but it's there so we'll support it since
889 * it's not all that hard.
890 */
891static void
892set80211nwkey(const char *val, int d, int s, const struct afswtch *rafp)
893{
894	int		txkey;
895	int		i, len;
896	u_int8_t	data[IEEE80211_KEYBUF_SIZE];
897
898	set80211(s, IEEE80211_IOC_WEP, IEEE80211_WEP_ON, 0, NULL);
899
900	if (isdigit((int)val[0]) && val[1] == ':') {
901		txkey = val[0]-'0'-1;
902		val += 2;
903
904		for (i = 0; i < 4; i++) {
905			bzero(data, sizeof(data));
906			len = sizeof(data);
907			val = get_string(val, ",", data, &len);
908			if (val == NULL)
909				exit(1);
910
911			set80211(s, IEEE80211_IOC_WEPKEY, i, len, data);
912		}
913	} else {
914		bzero(data, sizeof(data));
915		len = sizeof(data);
916		get_string(val, NULL, data, &len);
917		txkey = 0;
918
919		set80211(s, IEEE80211_IOC_WEPKEY, 0, len, data);
920
921		bzero(data, sizeof(data));
922		for (i = 1; i < 4; i++)
923			set80211(s, IEEE80211_IOC_WEPKEY, i, 0, data);
924	}
925
926	set80211(s, IEEE80211_IOC_WEPTXKEY, txkey, 0, NULL);
927}
928
929static void
930set80211rtsthreshold(const char *val, int d, int s, const struct afswtch *rafp)
931{
932	set80211(s, IEEE80211_IOC_RTSTHRESHOLD,
933		isundefarg(val) ? IEEE80211_RTS_MAX : atoi(val), 0, NULL);
934}
935
936static void
937set80211protmode(const char *val, int d, int s, const struct afswtch *rafp)
938{
939	int	mode;
940
941	if (strcasecmp(val, "off") == 0) {
942		mode = IEEE80211_PROTMODE_OFF;
943	} else if (strcasecmp(val, "cts") == 0) {
944		mode = IEEE80211_PROTMODE_CTS;
945	} else if (strncasecmp(val, "rtscts", 3) == 0) {
946		mode = IEEE80211_PROTMODE_RTSCTS;
947	} else {
948		errx(1, "unknown protection mode");
949	}
950
951	set80211(s, IEEE80211_IOC_PROTMODE, mode, 0, NULL);
952}
953
954static void
955set80211htprotmode(const char *val, int d, int s, const struct afswtch *rafp)
956{
957	int	mode;
958
959	if (strcasecmp(val, "off") == 0) {
960		mode = IEEE80211_PROTMODE_OFF;
961	} else if (strncasecmp(val, "rts", 3) == 0) {
962		mode = IEEE80211_PROTMODE_RTSCTS;
963	} else {
964		errx(1, "unknown protection mode");
965	}
966
967	set80211(s, IEEE80211_IOC_HTPROTMODE, mode, 0, NULL);
968}
969
970static void
971set80211txpower(const char *val, int d, int s, const struct afswtch *rafp)
972{
973	double v = atof(val);
974	int txpow;
975
976	txpow = (int) (2*v);
977	if (txpow != 2*v)
978		errx(-1, "invalid tx power (must be .5 dBm units)");
979	set80211(s, IEEE80211_IOC_TXPOWER, txpow, 0, NULL);
980}
981
982#define	IEEE80211_ROAMING_DEVICE	0
983#define	IEEE80211_ROAMING_AUTO		1
984#define	IEEE80211_ROAMING_MANUAL	2
985
986static void
987set80211roaming(const char *val, int d, int s, const struct afswtch *rafp)
988{
989	int mode;
990
991	if (strcasecmp(val, "device") == 0) {
992		mode = IEEE80211_ROAMING_DEVICE;
993	} else if (strcasecmp(val, "auto") == 0) {
994		mode = IEEE80211_ROAMING_AUTO;
995	} else if (strcasecmp(val, "manual") == 0) {
996		mode = IEEE80211_ROAMING_MANUAL;
997	} else {
998		errx(1, "unknown roaming mode");
999	}
1000	set80211(s, IEEE80211_IOC_ROAMING, mode, 0, NULL);
1001}
1002
1003static void
1004set80211wme(const char *val, int d, int s, const struct afswtch *rafp)
1005{
1006	set80211(s, IEEE80211_IOC_WME, d, 0, NULL);
1007}
1008
1009static void
1010set80211hidessid(const char *val, int d, int s, const struct afswtch *rafp)
1011{
1012	set80211(s, IEEE80211_IOC_HIDESSID, d, 0, NULL);
1013}
1014
1015static void
1016set80211apbridge(const char *val, int d, int s, const struct afswtch *rafp)
1017{
1018	set80211(s, IEEE80211_IOC_APBRIDGE, d, 0, NULL);
1019}
1020
1021static void
1022set80211fastframes(const char *val, int d, int s, const struct afswtch *rafp)
1023{
1024	set80211(s, IEEE80211_IOC_FF, d, 0, NULL);
1025}
1026
1027static void
1028set80211dturbo(const char *val, int d, int s, const struct afswtch *rafp)
1029{
1030	set80211(s, IEEE80211_IOC_TURBOP, d, 0, NULL);
1031}
1032
1033static void
1034set80211chanlist(const char *val, int d, int s, const struct afswtch *rafp)
1035{
1036	struct ieee80211req_chanlist chanlist;
1037	char *temp, *cp, *tp;
1038
1039	temp = malloc(strlen(val) + 1);
1040	if (temp == NULL)
1041		errx(1, "malloc failed");
1042	strcpy(temp, val);
1043	memset(&chanlist, 0, sizeof(chanlist));
1044	cp = temp;
1045	for (;;) {
1046		int first, last, f, c;
1047
1048		tp = strchr(cp, ',');
1049		if (tp != NULL)
1050			*tp++ = '\0';
1051		switch (sscanf(cp, "%u-%u", &first, &last)) {
1052		case 1:
1053			if (first > IEEE80211_CHAN_MAX)
1054				errx(-1, "channel %u out of range, max %u",
1055					first, IEEE80211_CHAN_MAX);
1056			setbit(chanlist.ic_channels, first);
1057			break;
1058		case 2:
1059			if (first > IEEE80211_CHAN_MAX)
1060				errx(-1, "channel %u out of range, max %u",
1061					first, IEEE80211_CHAN_MAX);
1062			if (last > IEEE80211_CHAN_MAX)
1063				errx(-1, "channel %u out of range, max %u",
1064					last, IEEE80211_CHAN_MAX);
1065			if (first > last)
1066				errx(-1, "void channel range, %u > %u",
1067					first, last);
1068			for (f = first; f <= last; f++)
1069				setbit(chanlist.ic_channels, f);
1070			break;
1071		}
1072		if (tp == NULL)
1073			break;
1074		c = *tp;
1075		while (isspace(c))
1076			tp++;
1077		if (!isdigit(c))
1078			break;
1079		cp = tp;
1080	}
1081	set80211(s, IEEE80211_IOC_CHANLIST, 0, sizeof(chanlist), &chanlist);
1082}
1083
1084static void
1085set80211bssid(const char *val, int d, int s, const struct afswtch *rafp)
1086{
1087
1088	if (!isanyarg(val)) {
1089		char *temp;
1090		struct sockaddr_dl sdl;
1091
1092		temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1093		if (temp == NULL)
1094			errx(1, "malloc failed");
1095		temp[0] = ':';
1096		strcpy(temp + 1, val);
1097		sdl.sdl_len = sizeof(sdl);
1098		link_addr(temp, &sdl);
1099		free(temp);
1100		if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1101			errx(1, "malformed link-level address");
1102		set80211(s, IEEE80211_IOC_BSSID, 0,
1103			IEEE80211_ADDR_LEN, LLADDR(&sdl));
1104	} else {
1105		uint8_t zerobssid[IEEE80211_ADDR_LEN];
1106		memset(zerobssid, 0, sizeof(zerobssid));
1107		set80211(s, IEEE80211_IOC_BSSID, 0,
1108			IEEE80211_ADDR_LEN, zerobssid);
1109	}
1110}
1111
1112static int
1113getac(const char *ac)
1114{
1115	if (strcasecmp(ac, "ac_be") == 0 || strcasecmp(ac, "be") == 0)
1116		return WME_AC_BE;
1117	if (strcasecmp(ac, "ac_bk") == 0 || strcasecmp(ac, "bk") == 0)
1118		return WME_AC_BK;
1119	if (strcasecmp(ac, "ac_vi") == 0 || strcasecmp(ac, "vi") == 0)
1120		return WME_AC_VI;
1121	if (strcasecmp(ac, "ac_vo") == 0 || strcasecmp(ac, "vo") == 0)
1122		return WME_AC_VO;
1123	errx(1, "unknown wme access class %s", ac);
1124}
1125
1126static
1127DECL_CMD_FUNC2(set80211cwmin, ac, val)
1128{
1129	set80211(s, IEEE80211_IOC_WME_CWMIN, atoi(val), getac(ac), NULL);
1130}
1131
1132static
1133DECL_CMD_FUNC2(set80211cwmax, ac, val)
1134{
1135	set80211(s, IEEE80211_IOC_WME_CWMAX, atoi(val), getac(ac), NULL);
1136}
1137
1138static
1139DECL_CMD_FUNC2(set80211aifs, ac, val)
1140{
1141	set80211(s, IEEE80211_IOC_WME_AIFS, atoi(val), getac(ac), NULL);
1142}
1143
1144static
1145DECL_CMD_FUNC2(set80211txoplimit, ac, val)
1146{
1147	set80211(s, IEEE80211_IOC_WME_TXOPLIMIT, atoi(val), getac(ac), NULL);
1148}
1149
1150static
1151DECL_CMD_FUNC(set80211acm, ac, d)
1152{
1153	set80211(s, IEEE80211_IOC_WME_ACM, 1, getac(ac), NULL);
1154}
1155static
1156DECL_CMD_FUNC(set80211noacm, ac, d)
1157{
1158	set80211(s, IEEE80211_IOC_WME_ACM, 0, getac(ac), NULL);
1159}
1160
1161static
1162DECL_CMD_FUNC(set80211ackpolicy, ac, d)
1163{
1164	set80211(s, IEEE80211_IOC_WME_ACKPOLICY, 1, getac(ac), NULL);
1165}
1166static
1167DECL_CMD_FUNC(set80211noackpolicy, ac, d)
1168{
1169	set80211(s, IEEE80211_IOC_WME_ACKPOLICY, 0, getac(ac), NULL);
1170}
1171
1172static
1173DECL_CMD_FUNC2(set80211bsscwmin, ac, val)
1174{
1175	set80211(s, IEEE80211_IOC_WME_CWMIN, atoi(val),
1176		getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1177}
1178
1179static
1180DECL_CMD_FUNC2(set80211bsscwmax, ac, val)
1181{
1182	set80211(s, IEEE80211_IOC_WME_CWMAX, atoi(val),
1183		getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1184}
1185
1186static
1187DECL_CMD_FUNC2(set80211bssaifs, ac, val)
1188{
1189	set80211(s, IEEE80211_IOC_WME_AIFS, atoi(val),
1190		getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1191}
1192
1193static
1194DECL_CMD_FUNC2(set80211bsstxoplimit, ac, val)
1195{
1196	set80211(s, IEEE80211_IOC_WME_TXOPLIMIT, atoi(val),
1197		getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1198}
1199
1200static
1201DECL_CMD_FUNC(set80211dtimperiod, val, d)
1202{
1203	set80211(s, IEEE80211_IOC_DTIM_PERIOD, atoi(val), 0, NULL);
1204}
1205
1206static
1207DECL_CMD_FUNC(set80211bintval, val, d)
1208{
1209	set80211(s, IEEE80211_IOC_BEACON_INTERVAL, atoi(val), 0, NULL);
1210}
1211
1212static void
1213set80211macmac(int s, int op, const char *val)
1214{
1215	char *temp;
1216	struct sockaddr_dl sdl;
1217
1218	temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1219	if (temp == NULL)
1220		errx(1, "malloc failed");
1221	temp[0] = ':';
1222	strcpy(temp + 1, val);
1223	sdl.sdl_len = sizeof(sdl);
1224	link_addr(temp, &sdl);
1225	free(temp);
1226	if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1227		errx(1, "malformed link-level address");
1228	set80211(s, op, 0, IEEE80211_ADDR_LEN, LLADDR(&sdl));
1229}
1230
1231static
1232DECL_CMD_FUNC(set80211addmac, val, d)
1233{
1234	set80211macmac(s, IEEE80211_IOC_ADDMAC, val);
1235}
1236
1237static
1238DECL_CMD_FUNC(set80211delmac, val, d)
1239{
1240	set80211macmac(s, IEEE80211_IOC_DELMAC, val);
1241}
1242
1243static
1244DECL_CMD_FUNC(set80211kickmac, val, d)
1245{
1246	char *temp;
1247	struct sockaddr_dl sdl;
1248	struct ieee80211req_mlme mlme;
1249
1250	temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1251	if (temp == NULL)
1252		errx(1, "malloc failed");
1253	temp[0] = ':';
1254	strcpy(temp + 1, val);
1255	sdl.sdl_len = sizeof(sdl);
1256	link_addr(temp, &sdl);
1257	free(temp);
1258	if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1259		errx(1, "malformed link-level address");
1260	memset(&mlme, 0, sizeof(mlme));
1261	mlme.im_op = IEEE80211_MLME_DEAUTH;
1262	mlme.im_reason = IEEE80211_REASON_AUTH_EXPIRE;
1263	memcpy(mlme.im_macaddr, LLADDR(&sdl), IEEE80211_ADDR_LEN);
1264	set80211(s, IEEE80211_IOC_MLME, 0, sizeof(mlme), &mlme);
1265}
1266
1267static
1268DECL_CMD_FUNC(set80211maccmd, val, d)
1269{
1270	set80211(s, IEEE80211_IOC_MACCMD, d, 0, NULL);
1271}
1272
1273static void
1274set80211meshrtmac(int s, int req, const char *val)
1275{
1276	char *temp;
1277	struct sockaddr_dl sdl;
1278
1279	temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1280	if (temp == NULL)
1281		errx(1, "malloc failed");
1282	temp[0] = ':';
1283	strcpy(temp + 1, val);
1284	sdl.sdl_len = sizeof(sdl);
1285	link_addr(temp, &sdl);
1286	free(temp);
1287	if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1288		errx(1, "malformed link-level address");
1289	set80211(s, IEEE80211_IOC_MESH_RTCMD, req,
1290	    IEEE80211_ADDR_LEN, LLADDR(&sdl));
1291}
1292
1293static
1294DECL_CMD_FUNC(set80211addmeshrt, val, d)
1295{
1296	set80211meshrtmac(s, IEEE80211_MESH_RTCMD_ADD, val);
1297}
1298
1299static
1300DECL_CMD_FUNC(set80211delmeshrt, val, d)
1301{
1302	set80211meshrtmac(s, IEEE80211_MESH_RTCMD_DELETE, val);
1303}
1304
1305static
1306DECL_CMD_FUNC(set80211meshrtcmd, val, d)
1307{
1308	set80211(s, IEEE80211_IOC_MESH_RTCMD, d, 0, NULL);
1309}
1310
1311static
1312DECL_CMD_FUNC(set80211hwmprootmode, val, d)
1313{
1314	int mode;
1315
1316	if (strcasecmp(val, "normal") == 0)
1317		mode = IEEE80211_HWMP_ROOTMODE_NORMAL;
1318	else if (strcasecmp(val, "proactive") == 0)
1319		mode = IEEE80211_HWMP_ROOTMODE_PROACTIVE;
1320	else if (strcasecmp(val, "rann") == 0)
1321		mode = IEEE80211_HWMP_ROOTMODE_RANN;
1322	else
1323		mode = IEEE80211_HWMP_ROOTMODE_DISABLED;
1324	set80211(s, IEEE80211_IOC_HWMP_ROOTMODE, mode, 0, NULL);
1325}
1326
1327static
1328DECL_CMD_FUNC(set80211hwmpmaxhops, val, d)
1329{
1330	set80211(s, IEEE80211_IOC_HWMP_MAXHOPS, atoi(val), 0, NULL);
1331}
1332
1333static void
1334set80211pureg(const char *val, int d, int s, const struct afswtch *rafp)
1335{
1336	set80211(s, IEEE80211_IOC_PUREG, d, 0, NULL);
1337}
1338
1339static void
1340set80211quiet(const char *val, int d, int s, const struct afswtch *rafp)
1341{
1342	set80211(s, IEEE80211_IOC_QUIET, d, 0, NULL);
1343}
1344
1345static
1346DECL_CMD_FUNC(set80211quietperiod, val, d)
1347{
1348	set80211(s, IEEE80211_IOC_QUIET_PERIOD, atoi(val), 0, NULL);
1349}
1350
1351static
1352DECL_CMD_FUNC(set80211quietcount, val, d)
1353{
1354	set80211(s, IEEE80211_IOC_QUIET_COUNT, atoi(val), 0, NULL);
1355}
1356
1357static
1358DECL_CMD_FUNC(set80211quietduration, val, d)
1359{
1360	set80211(s, IEEE80211_IOC_QUIET_DUR, atoi(val), 0, NULL);
1361}
1362
1363static
1364DECL_CMD_FUNC(set80211quietoffset, val, d)
1365{
1366	set80211(s, IEEE80211_IOC_QUIET_OFFSET, atoi(val), 0, NULL);
1367}
1368
1369static void
1370set80211bgscan(const char *val, int d, int s, const struct afswtch *rafp)
1371{
1372	set80211(s, IEEE80211_IOC_BGSCAN, d, 0, NULL);
1373}
1374
1375static
1376DECL_CMD_FUNC(set80211bgscanidle, val, d)
1377{
1378	set80211(s, IEEE80211_IOC_BGSCAN_IDLE, atoi(val), 0, NULL);
1379}
1380
1381static
1382DECL_CMD_FUNC(set80211bgscanintvl, val, d)
1383{
1384	set80211(s, IEEE80211_IOC_BGSCAN_INTERVAL, atoi(val), 0, NULL);
1385}
1386
1387static
1388DECL_CMD_FUNC(set80211scanvalid, val, d)
1389{
1390	set80211(s, IEEE80211_IOC_SCANVALID, atoi(val), 0, NULL);
1391}
1392
1393/*
1394 * Parse an optional trailing specification of which netbands
1395 * to apply a parameter to.  This is basically the same syntax
1396 * as used for channels but you can concatenate to specify
1397 * multiple.  For example:
1398 *	14:abg		apply to 11a, 11b, and 11g
1399 *	6:ht		apply to 11na and 11ng
1400 * We don't make a big effort to catch silly things; this is
1401 * really a convenience mechanism.
1402 */
1403static int
1404getmodeflags(const char *val)
1405{
1406	const char *cp;
1407	int flags;
1408
1409	flags = 0;
1410
1411	cp = strchr(val, ':');
1412	if (cp != NULL) {
1413		for (cp++; isalpha((int) *cp); cp++) {
1414			/* accept mixed case */
1415			int c = *cp;
1416			if (isupper(c))
1417				c = tolower(c);
1418			switch (c) {
1419			case 'a':		/* 802.11a */
1420				flags |= IEEE80211_CHAN_A;
1421				break;
1422			case 'b':		/* 802.11b */
1423				flags |= IEEE80211_CHAN_B;
1424				break;
1425			case 'g':		/* 802.11g */
1426				flags |= IEEE80211_CHAN_G;
1427				break;
1428			case 'n':		/* 802.11n */
1429				flags |= IEEE80211_CHAN_HT;
1430				break;
1431			case 'd':		/* dt = Atheros Dynamic Turbo */
1432				flags |= IEEE80211_CHAN_TURBO;
1433				break;
1434			case 't':		/* ht, dt, st, t */
1435				/* dt and unadorned t specify Dynamic Turbo */
1436				if ((flags & (IEEE80211_CHAN_STURBO|IEEE80211_CHAN_HT)) == 0)
1437					flags |= IEEE80211_CHAN_TURBO;
1438				break;
1439			case 's':		/* st = Atheros Static Turbo */
1440				flags |= IEEE80211_CHAN_STURBO;
1441				break;
1442			case 'h':		/* 1/2-width channels */
1443				flags |= IEEE80211_CHAN_HALF;
1444				break;
1445			case 'q':		/* 1/4-width channels */
1446				flags |= IEEE80211_CHAN_QUARTER;
1447				break;
1448			default:
1449				errx(-1, "%s: Invalid mode attribute %c\n",
1450				    val, *cp);
1451			}
1452		}
1453	}
1454	return flags;
1455}
1456
1457#define	IEEE80211_CHAN_HTA	(IEEE80211_CHAN_HT|IEEE80211_CHAN_5GHZ)
1458#define	IEEE80211_CHAN_HTG	(IEEE80211_CHAN_HT|IEEE80211_CHAN_2GHZ)
1459
1460#define	_APPLY(_flags, _base, _param, _v) do {				\
1461    if (_flags & IEEE80211_CHAN_HT) {					\
1462	    if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
1463		    _base.params[IEEE80211_MODE_11NA]._param = _v;	\
1464		    _base.params[IEEE80211_MODE_11NG]._param = _v;	\
1465	    } else if (_flags & IEEE80211_CHAN_5GHZ)			\
1466		    _base.params[IEEE80211_MODE_11NA]._param = _v;	\
1467	    else							\
1468		    _base.params[IEEE80211_MODE_11NG]._param = _v;	\
1469    }									\
1470    if (_flags & IEEE80211_CHAN_TURBO) {				\
1471	    if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
1472		    _base.params[IEEE80211_MODE_TURBO_A]._param = _v;	\
1473		    _base.params[IEEE80211_MODE_TURBO_G]._param = _v;	\
1474	    } else if (_flags & IEEE80211_CHAN_5GHZ)			\
1475		    _base.params[IEEE80211_MODE_TURBO_A]._param = _v;	\
1476	    else							\
1477		    _base.params[IEEE80211_MODE_TURBO_G]._param = _v;	\
1478    }									\
1479    if (_flags & IEEE80211_CHAN_STURBO)					\
1480	    _base.params[IEEE80211_MODE_STURBO_A]._param = _v;		\
1481    if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)		\
1482	    _base.params[IEEE80211_MODE_11A]._param = _v;		\
1483    if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)		\
1484	    _base.params[IEEE80211_MODE_11G]._param = _v;		\
1485    if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)		\
1486	    _base.params[IEEE80211_MODE_11B]._param = _v;		\
1487    if (_flags & IEEE80211_CHAN_HALF)					\
1488	    _base.params[IEEE80211_MODE_HALF]._param = _v;		\
1489    if (_flags & IEEE80211_CHAN_QUARTER)				\
1490	    _base.params[IEEE80211_MODE_QUARTER]._param = _v;		\
1491} while (0)
1492#define	_APPLY1(_flags, _base, _param, _v) do {				\
1493    if (_flags & IEEE80211_CHAN_HT) {					\
1494	    if (_flags & IEEE80211_CHAN_5GHZ)				\
1495		    _base.params[IEEE80211_MODE_11NA]._param = _v;	\
1496	    else							\
1497		    _base.params[IEEE80211_MODE_11NG]._param = _v;	\
1498    } else if ((_flags & IEEE80211_CHAN_108A) == IEEE80211_CHAN_108A)	\
1499	    _base.params[IEEE80211_MODE_TURBO_A]._param = _v;		\
1500    else if ((_flags & IEEE80211_CHAN_108G) == IEEE80211_CHAN_108G)	\
1501	    _base.params[IEEE80211_MODE_TURBO_G]._param = _v;		\
1502    else if ((_flags & IEEE80211_CHAN_ST) == IEEE80211_CHAN_ST)		\
1503	    _base.params[IEEE80211_MODE_STURBO_A]._param = _v;		\
1504    else if (_flags & IEEE80211_CHAN_HALF)				\
1505	    _base.params[IEEE80211_MODE_HALF]._param = _v;		\
1506    else if (_flags & IEEE80211_CHAN_QUARTER)				\
1507	    _base.params[IEEE80211_MODE_QUARTER]._param = _v;		\
1508    else if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)		\
1509	    _base.params[IEEE80211_MODE_11A]._param = _v;		\
1510    else if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)		\
1511	    _base.params[IEEE80211_MODE_11G]._param = _v;		\
1512    else if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)		\
1513	    _base.params[IEEE80211_MODE_11B]._param = _v;		\
1514} while (0)
1515#define	_APPLY_RATE(_flags, _base, _param, _v) do {			\
1516    if (_flags & IEEE80211_CHAN_HT) {					\
1517	(_v) = (_v / 2) | IEEE80211_RATE_MCS;				\
1518    }									\
1519    _APPLY(_flags, _base, _param, _v);					\
1520} while (0)
1521#define	_APPLY_RATE1(_flags, _base, _param, _v) do {			\
1522    if (_flags & IEEE80211_CHAN_HT) {					\
1523	(_v) = (_v / 2) | IEEE80211_RATE_MCS;				\
1524    }									\
1525    _APPLY1(_flags, _base, _param, _v);					\
1526} while (0)
1527
1528static
1529DECL_CMD_FUNC(set80211roamrssi, val, d)
1530{
1531	double v = atof(val);
1532	int rssi, flags;
1533
1534	rssi = (int) (2*v);
1535	if (rssi != 2*v)
1536		errx(-1, "invalid rssi (must be .5 dBm units)");
1537	flags = getmodeflags(val);
1538	getroam(s);
1539	if (flags == 0) {		/* NB: no flags => current channel */
1540		flags = getcurchan(s)->ic_flags;
1541		_APPLY1(flags, roamparams, rssi, rssi);
1542	} else
1543		_APPLY(flags, roamparams, rssi, rssi);
1544	callback_register(setroam_cb, &roamparams);
1545}
1546
1547static int
1548getrate(const char *val, const char *tag)
1549{
1550	double v = atof(val);
1551	int rate;
1552
1553	rate = (int) (2*v);
1554	if (rate != 2*v)
1555		errx(-1, "invalid %s rate (must be .5 Mb/s units)", tag);
1556	return rate;		/* NB: returns 2x the specified value */
1557}
1558
1559static
1560DECL_CMD_FUNC(set80211roamrate, val, d)
1561{
1562	int rate, flags;
1563
1564	rate = getrate(val, "roam");
1565	flags = getmodeflags(val);
1566	getroam(s);
1567	if (flags == 0) {		/* NB: no flags => current channel */
1568		flags = getcurchan(s)->ic_flags;
1569		_APPLY_RATE1(flags, roamparams, rate, rate);
1570	} else
1571		_APPLY_RATE(flags, roamparams, rate, rate);
1572	callback_register(setroam_cb, &roamparams);
1573}
1574
1575static
1576DECL_CMD_FUNC(set80211mcastrate, val, d)
1577{
1578	int rate, flags;
1579
1580	rate = getrate(val, "mcast");
1581	flags = getmodeflags(val);
1582	gettxparams(s);
1583	if (flags == 0) {		/* NB: no flags => current channel */
1584		flags = getcurchan(s)->ic_flags;
1585		_APPLY_RATE1(flags, txparams, mcastrate, rate);
1586	} else
1587		_APPLY_RATE(flags, txparams, mcastrate, rate);
1588	callback_register(settxparams_cb, &txparams);
1589}
1590
1591static
1592DECL_CMD_FUNC(set80211mgtrate, val, d)
1593{
1594	int rate, flags;
1595
1596	rate = getrate(val, "mgmt");
1597	flags = getmodeflags(val);
1598	gettxparams(s);
1599	if (flags == 0) {		/* NB: no flags => current channel */
1600		flags = getcurchan(s)->ic_flags;
1601		_APPLY_RATE1(flags, txparams, mgmtrate, rate);
1602	} else
1603		_APPLY_RATE(flags, txparams, mgmtrate, rate);
1604	callback_register(settxparams_cb, &txparams);
1605}
1606
1607static
1608DECL_CMD_FUNC(set80211ucastrate, val, d)
1609{
1610	int flags;
1611
1612	gettxparams(s);
1613	flags = getmodeflags(val);
1614	if (isanyarg(val)) {
1615		if (flags == 0) {	/* NB: no flags => current channel */
1616			flags = getcurchan(s)->ic_flags;
1617			_APPLY1(flags, txparams, ucastrate,
1618			    IEEE80211_FIXED_RATE_NONE);
1619		} else
1620			_APPLY(flags, txparams, ucastrate,
1621			    IEEE80211_FIXED_RATE_NONE);
1622	} else {
1623		int rate = getrate(val, "ucast");
1624		if (flags == 0) {	/* NB: no flags => current channel */
1625			flags = getcurchan(s)->ic_flags;
1626			_APPLY_RATE1(flags, txparams, ucastrate, rate);
1627		} else
1628			_APPLY_RATE(flags, txparams, ucastrate, rate);
1629	}
1630	callback_register(settxparams_cb, &txparams);
1631}
1632
1633static
1634DECL_CMD_FUNC(set80211maxretry, val, d)
1635{
1636	int v = atoi(val), flags;
1637
1638	flags = getmodeflags(val);
1639	gettxparams(s);
1640	if (flags == 0) {		/* NB: no flags => current channel */
1641		flags = getcurchan(s)->ic_flags;
1642		_APPLY1(flags, txparams, maxretry, v);
1643	} else
1644		_APPLY(flags, txparams, maxretry, v);
1645	callback_register(settxparams_cb, &txparams);
1646}
1647#undef _APPLY_RATE
1648#undef _APPLY
1649#undef IEEE80211_CHAN_HTA
1650#undef IEEE80211_CHAN_HTG
1651
1652static
1653DECL_CMD_FUNC(set80211fragthreshold, val, d)
1654{
1655	set80211(s, IEEE80211_IOC_FRAGTHRESHOLD,
1656		isundefarg(val) ? IEEE80211_FRAG_MAX : atoi(val), 0, NULL);
1657}
1658
1659static
1660DECL_CMD_FUNC(set80211bmissthreshold, val, d)
1661{
1662	set80211(s, IEEE80211_IOC_BMISSTHRESHOLD,
1663		isundefarg(val) ? IEEE80211_HWBMISS_MAX : atoi(val), 0, NULL);
1664}
1665
1666static void
1667set80211burst(const char *val, int d, int s, const struct afswtch *rafp)
1668{
1669	set80211(s, IEEE80211_IOC_BURST, d, 0, NULL);
1670}
1671
1672static void
1673set80211doth(const char *val, int d, int s, const struct afswtch *rafp)
1674{
1675	set80211(s, IEEE80211_IOC_DOTH, d, 0, NULL);
1676}
1677
1678static void
1679set80211dfs(const char *val, int d, int s, const struct afswtch *rafp)
1680{
1681	set80211(s, IEEE80211_IOC_DFS, d, 0, NULL);
1682}
1683
1684static void
1685set80211shortgi(const char *val, int d, int s, const struct afswtch *rafp)
1686{
1687	set80211(s, IEEE80211_IOC_SHORTGI,
1688		d ? (IEEE80211_HTCAP_SHORTGI20 | IEEE80211_HTCAP_SHORTGI40) : 0,
1689		0, NULL);
1690}
1691
1692static void
1693set80211ampdu(const char *val, int d, int s, const struct afswtch *rafp)
1694{
1695	int ampdu;
1696
1697	if (get80211val(s, IEEE80211_IOC_AMPDU, &ampdu) < 0)
1698		errx(-1, "cannot get AMPDU setting");
1699	if (d < 0) {
1700		d = -d;
1701		ampdu &= ~d;
1702	} else
1703		ampdu |= d;
1704	set80211(s, IEEE80211_IOC_AMPDU, ampdu, 0, NULL);
1705}
1706
1707static
1708DECL_CMD_FUNC(set80211ampdulimit, val, d)
1709{
1710	int v;
1711
1712	switch (atoi(val)) {
1713	case 8:
1714	case 8*1024:
1715		v = IEEE80211_HTCAP_MAXRXAMPDU_8K;
1716		break;
1717	case 16:
1718	case 16*1024:
1719		v = IEEE80211_HTCAP_MAXRXAMPDU_16K;
1720		break;
1721	case 32:
1722	case 32*1024:
1723		v = IEEE80211_HTCAP_MAXRXAMPDU_32K;
1724		break;
1725	case 64:
1726	case 64*1024:
1727		v = IEEE80211_HTCAP_MAXRXAMPDU_64K;
1728		break;
1729	default:
1730		errx(-1, "invalid A-MPDU limit %s", val);
1731	}
1732	set80211(s, IEEE80211_IOC_AMPDU_LIMIT, v, 0, NULL);
1733}
1734
1735static
1736DECL_CMD_FUNC(set80211ampdudensity, val, d)
1737{
1738	int v;
1739
1740	if (isanyarg(val) || strcasecmp(val, "na") == 0)
1741		v = IEEE80211_HTCAP_MPDUDENSITY_NA;
1742	else switch ((int)(atof(val)*4)) {
1743	case 0:
1744		v = IEEE80211_HTCAP_MPDUDENSITY_NA;
1745		break;
1746	case 1:
1747		v = IEEE80211_HTCAP_MPDUDENSITY_025;
1748		break;
1749	case 2:
1750		v = IEEE80211_HTCAP_MPDUDENSITY_05;
1751		break;
1752	case 4:
1753		v = IEEE80211_HTCAP_MPDUDENSITY_1;
1754		break;
1755	case 8:
1756		v = IEEE80211_HTCAP_MPDUDENSITY_2;
1757		break;
1758	case 16:
1759		v = IEEE80211_HTCAP_MPDUDENSITY_4;
1760		break;
1761	case 32:
1762		v = IEEE80211_HTCAP_MPDUDENSITY_8;
1763		break;
1764	case 64:
1765		v = IEEE80211_HTCAP_MPDUDENSITY_16;
1766		break;
1767	default:
1768		errx(-1, "invalid A-MPDU density %s", val);
1769	}
1770	set80211(s, IEEE80211_IOC_AMPDU_DENSITY, v, 0, NULL);
1771}
1772
1773static void
1774set80211amsdu(const char *val, int d, int s, const struct afswtch *rafp)
1775{
1776	int amsdu;
1777
1778	if (get80211val(s, IEEE80211_IOC_AMSDU, &amsdu) < 0)
1779		err(-1, "cannot get AMSDU setting");
1780	if (d < 0) {
1781		d = -d;
1782		amsdu &= ~d;
1783	} else
1784		amsdu |= d;
1785	set80211(s, IEEE80211_IOC_AMSDU, amsdu, 0, NULL);
1786}
1787
1788static
1789DECL_CMD_FUNC(set80211amsdulimit, val, d)
1790{
1791	set80211(s, IEEE80211_IOC_AMSDU_LIMIT, atoi(val), 0, NULL);
1792}
1793
1794static void
1795set80211puren(const char *val, int d, int s, const struct afswtch *rafp)
1796{
1797	set80211(s, IEEE80211_IOC_PUREN, d, 0, NULL);
1798}
1799
1800static void
1801set80211htcompat(const char *val, int d, int s, const struct afswtch *rafp)
1802{
1803	set80211(s, IEEE80211_IOC_HTCOMPAT, d, 0, NULL);
1804}
1805
1806static void
1807set80211htconf(const char *val, int d, int s, const struct afswtch *rafp)
1808{
1809	set80211(s, IEEE80211_IOC_HTCONF, d, 0, NULL);
1810	htconf = d;
1811}
1812
1813static void
1814set80211dwds(const char *val, int d, int s, const struct afswtch *rafp)
1815{
1816	set80211(s, IEEE80211_IOC_DWDS, d, 0, NULL);
1817}
1818
1819static void
1820set80211inact(const char *val, int d, int s, const struct afswtch *rafp)
1821{
1822	set80211(s, IEEE80211_IOC_INACTIVITY, d, 0, NULL);
1823}
1824
1825static void
1826set80211tsn(const char *val, int d, int s, const struct afswtch *rafp)
1827{
1828	set80211(s, IEEE80211_IOC_TSN, d, 0, NULL);
1829}
1830
1831static void
1832set80211dotd(const char *val, int d, int s, const struct afswtch *rafp)
1833{
1834	set80211(s, IEEE80211_IOC_DOTD, d, 0, NULL);
1835}
1836
1837static void
1838set80211smps(const char *val, int d, int s, const struct afswtch *rafp)
1839{
1840	set80211(s, IEEE80211_IOC_SMPS, d, 0, NULL);
1841}
1842
1843static void
1844set80211rifs(const char *val, int d, int s, const struct afswtch *rafp)
1845{
1846	set80211(s, IEEE80211_IOC_RIFS, d, 0, NULL);
1847}
1848
1849static
1850DECL_CMD_FUNC(set80211tdmaslot, val, d)
1851{
1852	set80211(s, IEEE80211_IOC_TDMA_SLOT, atoi(val), 0, NULL);
1853}
1854
1855static
1856DECL_CMD_FUNC(set80211tdmaslotcnt, val, d)
1857{
1858	set80211(s, IEEE80211_IOC_TDMA_SLOTCNT, atoi(val), 0, NULL);
1859}
1860
1861static
1862DECL_CMD_FUNC(set80211tdmaslotlen, val, d)
1863{
1864	set80211(s, IEEE80211_IOC_TDMA_SLOTLEN, atoi(val), 0, NULL);
1865}
1866
1867static
1868DECL_CMD_FUNC(set80211tdmabintval, val, d)
1869{
1870	set80211(s, IEEE80211_IOC_TDMA_BINTERVAL, atoi(val), 0, NULL);
1871}
1872
1873static
1874DECL_CMD_FUNC(set80211meshttl, val, d)
1875{
1876	set80211(s, IEEE80211_IOC_MESH_TTL, atoi(val), 0, NULL);
1877}
1878
1879static
1880DECL_CMD_FUNC(set80211meshforward, val, d)
1881{
1882	set80211(s, IEEE80211_IOC_MESH_FWRD, atoi(val), 0, NULL);
1883}
1884
1885static
1886DECL_CMD_FUNC(set80211meshpeering, val, d)
1887{
1888	set80211(s, IEEE80211_IOC_MESH_AP, atoi(val), 0, NULL);
1889}
1890
1891static
1892DECL_CMD_FUNC(set80211meshmetric, val, d)
1893{
1894	char v[12];
1895
1896	memcpy(v, val, sizeof(v));
1897	set80211(s, IEEE80211_IOC_MESH_PR_METRIC, 0, 0, v);
1898}
1899
1900static
1901DECL_CMD_FUNC(set80211meshpath, val, d)
1902{
1903	char v[12];
1904
1905	memcpy(v, val, sizeof(v));
1906	set80211(s, IEEE80211_IOC_MESH_PR_PATH, 0, 0, v);
1907}
1908
1909static int
1910regdomain_sort(const void *a, const void *b)
1911{
1912#define	CHAN_ALL \
1913	(IEEE80211_CHAN_ALLTURBO|IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER)
1914	const struct ieee80211_channel *ca = a;
1915	const struct ieee80211_channel *cb = b;
1916
1917	return ca->ic_freq == cb->ic_freq ?
1918	    (ca->ic_flags & CHAN_ALL) - (cb->ic_flags & CHAN_ALL) :
1919	    ca->ic_freq - cb->ic_freq;
1920#undef CHAN_ALL
1921}
1922
1923static const struct ieee80211_channel *
1924chanlookup(const struct ieee80211_channel chans[], int nchans,
1925	int freq, int flags)
1926{
1927	int i;
1928
1929	flags &= IEEE80211_CHAN_ALLTURBO;
1930	for (i = 0; i < nchans; i++) {
1931		const struct ieee80211_channel *c = &chans[i];
1932		if (c->ic_freq == freq &&
1933		    (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
1934			return c;
1935	}
1936	return NULL;
1937}
1938
1939static int
1940chanfind(const struct ieee80211_channel chans[], int nchans, int flags)
1941{
1942	int i;
1943
1944	for (i = 0; i < nchans; i++) {
1945		const struct ieee80211_channel *c = &chans[i];
1946		if ((c->ic_flags & flags) == flags)
1947			return 1;
1948	}
1949	return 0;
1950}
1951
1952/*
1953 * Check channel compatibility.
1954 */
1955static int
1956checkchan(const struct ieee80211req_chaninfo *avail, int freq, int flags)
1957{
1958	flags &= ~REQ_FLAGS;
1959	/*
1960	 * Check if exact channel is in the calibration table;
1961	 * everything below is to deal with channels that we
1962	 * want to include but that are not explicitly listed.
1963	 */
1964	if (flags & IEEE80211_CHAN_HT40) {
1965		/* NB: we use an HT40 channel center that matches HT20 */
1966		flags = (flags &~ IEEE80211_CHAN_HT40) | IEEE80211_CHAN_HT20;
1967	}
1968	if (chanlookup(avail->ic_chans, avail->ic_nchans, freq, flags) != NULL)
1969		return 1;
1970	if (flags & IEEE80211_CHAN_GSM) {
1971		/*
1972		 * XXX GSM frequency mapping is handled in the kernel
1973		 * so we cannot find them in the calibration table;
1974		 * just accept the channel and the kernel will reject
1975		 * the channel list if it's wrong.
1976		 */
1977		return 1;
1978	}
1979	/*
1980	 * If this is a 1/2 or 1/4 width channel allow it if a full
1981	 * width channel is present for this frequency, and the device
1982	 * supports fractional channels on this band.  This is a hack
1983	 * that avoids bloating the calibration table; it may be better
1984	 * by per-band attributes though (we are effectively calculating
1985	 * this attribute by scanning the channel list ourself).
1986	 */
1987	if ((flags & (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == 0)
1988		return 0;
1989	if (chanlookup(avail->ic_chans, avail->ic_nchans, freq,
1990	    flags &~ (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == NULL)
1991		return 0;
1992	if (flags & IEEE80211_CHAN_HALF) {
1993		return chanfind(avail->ic_chans, avail->ic_nchans,
1994		    IEEE80211_CHAN_HALF |
1995		       (flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
1996	} else {
1997		return chanfind(avail->ic_chans, avail->ic_nchans,
1998		    IEEE80211_CHAN_QUARTER |
1999			(flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
2000	}
2001}
2002
2003static void
2004regdomain_addchans(struct ieee80211req_chaninfo *ci,
2005	const netband_head *bands,
2006	const struct ieee80211_regdomain *reg,
2007	uint32_t chanFlags,
2008	const struct ieee80211req_chaninfo *avail)
2009{
2010	const struct netband *nb;
2011	const struct freqband *b;
2012	struct ieee80211_channel *c, *prev;
2013	int freq, hi_adj, lo_adj, channelSep;
2014	uint32_t flags;
2015
2016	hi_adj = (chanFlags & IEEE80211_CHAN_HT40U) ? -20 : 0;
2017	lo_adj = (chanFlags & IEEE80211_CHAN_HT40D) ? 20 : 0;
2018	channelSep = (chanFlags & IEEE80211_CHAN_2GHZ) ? 0 : 40;
2019	LIST_FOREACH(nb, bands, next) {
2020		b = nb->band;
2021		if (verbose) {
2022			printf("%s:", __func__);
2023			printb(" chanFlags", chanFlags, IEEE80211_CHAN_BITS);
2024			printb(" bandFlags", nb->flags | b->flags,
2025			    IEEE80211_CHAN_BITS);
2026			putchar('\n');
2027		}
2028		prev = NULL;
2029		for (freq = b->freqStart + lo_adj;
2030		     freq <= b->freqEnd + hi_adj; freq += b->chanSep) {
2031			/*
2032			 * Construct flags for the new channel.  We take
2033			 * the attributes from the band descriptions except
2034			 * for HT40 which is enabled generically (i.e. +/-
2035			 * extension channel) in the band description and
2036			 * then constrained according by channel separation.
2037			 */
2038			flags = nb->flags | b->flags;
2039			if (flags & IEEE80211_CHAN_HT) {
2040				/*
2041				 * HT channels are generated specially; we're
2042				 * called to add HT20, HT40+, and HT40- chan's
2043				 * so we need to expand only band specs for
2044				 * the HT channel type being added.
2045				 */
2046				if ((chanFlags & IEEE80211_CHAN_HT20) &&
2047				    (flags & IEEE80211_CHAN_HT20) == 0) {
2048					if (verbose)
2049						printf("%u: skip, not an "
2050						    "HT20 channel\n", freq);
2051					continue;
2052				}
2053				if ((chanFlags & IEEE80211_CHAN_HT40) &&
2054				    (flags & IEEE80211_CHAN_HT40) == 0) {
2055					if (verbose)
2056						printf("%u: skip, not an "
2057						    "HT40 channel\n", freq);
2058					continue;
2059				}
2060				/* NB: HT attribute comes from caller */
2061				flags &= ~IEEE80211_CHAN_HT;
2062				flags |= chanFlags & IEEE80211_CHAN_HT;
2063			}
2064			/*
2065			 * Check if device can operate on this frequency.
2066			 */
2067			if (!checkchan(avail, freq, flags)) {
2068				if (verbose) {
2069					printf("%u: skip, ", freq);
2070					printb("flags", flags,
2071					    IEEE80211_CHAN_BITS);
2072					printf(" not available\n");
2073				}
2074				continue;
2075			}
2076			if ((flags & REQ_ECM) && !reg->ecm) {
2077				if (verbose)
2078					printf("%u: skip, ECM channel\n", freq);
2079				continue;
2080			}
2081			if ((flags & REQ_INDOOR) && reg->location == 'O') {
2082				if (verbose)
2083					printf("%u: skip, indoor channel\n",
2084					    freq);
2085				continue;
2086			}
2087			if ((flags & REQ_OUTDOOR) && reg->location == 'I') {
2088				if (verbose)
2089					printf("%u: skip, outdoor channel\n",
2090					    freq);
2091				continue;
2092			}
2093			if ((flags & IEEE80211_CHAN_HT40) &&
2094			    prev != NULL && (freq - prev->ic_freq) < channelSep) {
2095				if (verbose)
2096					printf("%u: skip, only %u channel "
2097					    "separation, need %d\n", freq,
2098					    freq - prev->ic_freq, channelSep);
2099				continue;
2100			}
2101			if (ci->ic_nchans == IEEE80211_CHAN_MAX) {
2102				if (verbose)
2103					printf("%u: skip, channel table full\n",
2104					    freq);
2105				break;
2106			}
2107			c = &ci->ic_chans[ci->ic_nchans++];
2108			memset(c, 0, sizeof(*c));
2109			c->ic_freq = freq;
2110			c->ic_flags = flags;
2111			if (c->ic_flags & IEEE80211_CHAN_DFS)
2112				c->ic_maxregpower = nb->maxPowerDFS;
2113			else
2114				c->ic_maxregpower = nb->maxPower;
2115			if (verbose) {
2116				printf("[%3d] add freq %u ",
2117				    ci->ic_nchans-1, c->ic_freq);
2118				printb("flags", c->ic_flags, IEEE80211_CHAN_BITS);
2119				printf(" power %u\n", c->ic_maxregpower);
2120			}
2121			/* NB: kernel fills in other fields */
2122			prev = c;
2123		}
2124	}
2125}
2126
2127static void
2128regdomain_makechannels(
2129	struct ieee80211_regdomain_req *req,
2130	const struct ieee80211_devcaps_req *dc)
2131{
2132	struct regdata *rdp = getregdata();
2133	const struct country *cc;
2134	const struct ieee80211_regdomain *reg = &req->rd;
2135	struct ieee80211req_chaninfo *ci = &req->chaninfo;
2136	const struct regdomain *rd;
2137
2138	/*
2139	 * Locate construction table for new channel list.  We treat
2140	 * the regdomain/SKU as definitive so a country can be in
2141	 * multiple with different properties (e.g. US in FCC+FCC3).
2142	 * If no regdomain is specified then we fallback on the country
2143	 * code to find the associated regdomain since countries always
2144	 * belong to at least one regdomain.
2145	 */
2146	if (reg->regdomain == 0) {
2147		cc = lib80211_country_findbycc(rdp, reg->country);
2148		if (cc == NULL)
2149			errx(1, "internal error, country %d not found",
2150			    reg->country);
2151		rd = cc->rd;
2152	} else
2153		rd = lib80211_regdomain_findbysku(rdp, reg->regdomain);
2154	if (rd == NULL)
2155		errx(1, "internal error, regdomain %d not found",
2156			    reg->regdomain);
2157	if (rd->sku != SKU_DEBUG) {
2158		/*
2159		 * regdomain_addchans incrememnts the channel count for
2160		 * each channel it adds so initialize ic_nchans to zero.
2161		 * Note that we know we have enough space to hold all possible
2162		 * channels because the devcaps list size was used to
2163		 * allocate our request.
2164		 */
2165		ci->ic_nchans = 0;
2166		if (!LIST_EMPTY(&rd->bands_11b))
2167			regdomain_addchans(ci, &rd->bands_11b, reg,
2168			    IEEE80211_CHAN_B, &dc->dc_chaninfo);
2169		if (!LIST_EMPTY(&rd->bands_11g))
2170			regdomain_addchans(ci, &rd->bands_11g, reg,
2171			    IEEE80211_CHAN_G, &dc->dc_chaninfo);
2172		if (!LIST_EMPTY(&rd->bands_11a))
2173			regdomain_addchans(ci, &rd->bands_11a, reg,
2174			    IEEE80211_CHAN_A, &dc->dc_chaninfo);
2175		if (!LIST_EMPTY(&rd->bands_11na) && dc->dc_htcaps != 0) {
2176			regdomain_addchans(ci, &rd->bands_11na, reg,
2177			    IEEE80211_CHAN_A | IEEE80211_CHAN_HT20,
2178			    &dc->dc_chaninfo);
2179			if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2180				regdomain_addchans(ci, &rd->bands_11na, reg,
2181				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U,
2182				    &dc->dc_chaninfo);
2183				regdomain_addchans(ci, &rd->bands_11na, reg,
2184				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D,
2185				    &dc->dc_chaninfo);
2186			}
2187		}
2188		if (!LIST_EMPTY(&rd->bands_11ng) && dc->dc_htcaps != 0) {
2189			regdomain_addchans(ci, &rd->bands_11ng, reg,
2190			    IEEE80211_CHAN_G | IEEE80211_CHAN_HT20,
2191			    &dc->dc_chaninfo);
2192			if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2193				regdomain_addchans(ci, &rd->bands_11ng, reg,
2194				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U,
2195				    &dc->dc_chaninfo);
2196				regdomain_addchans(ci, &rd->bands_11ng, reg,
2197				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D,
2198				    &dc->dc_chaninfo);
2199			}
2200		}
2201		qsort(ci->ic_chans, ci->ic_nchans, sizeof(ci->ic_chans[0]),
2202		    regdomain_sort);
2203	} else
2204		memcpy(ci, &dc->dc_chaninfo,
2205		    IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
2206}
2207
2208static void
2209list_countries(void)
2210{
2211	struct regdata *rdp = getregdata();
2212	const struct country *cp;
2213	const struct regdomain *dp;
2214	int i;
2215
2216	i = 0;
2217	printf("\nCountry codes:\n");
2218	LIST_FOREACH(cp, &rdp->countries, next) {
2219		printf("%2s %-15.15s%s", cp->isoname,
2220		    cp->name, ((i+1)%4) == 0 ? "\n" : " ");
2221		i++;
2222	}
2223	i = 0;
2224	printf("\nRegulatory domains:\n");
2225	LIST_FOREACH(dp, &rdp->domains, next) {
2226		printf("%-15.15s%s", dp->name, ((i+1)%4) == 0 ? "\n" : " ");
2227		i++;
2228	}
2229	printf("\n");
2230}
2231
2232static void
2233defaultcountry(const struct regdomain *rd)
2234{
2235	struct regdata *rdp = getregdata();
2236	const struct country *cc;
2237
2238	cc = lib80211_country_findbycc(rdp, rd->cc->code);
2239	if (cc == NULL)
2240		errx(1, "internal error, ISO country code %d not "
2241		    "defined for regdomain %s", rd->cc->code, rd->name);
2242	regdomain.country = cc->code;
2243	regdomain.isocc[0] = cc->isoname[0];
2244	regdomain.isocc[1] = cc->isoname[1];
2245}
2246
2247static
2248DECL_CMD_FUNC(set80211regdomain, val, d)
2249{
2250	struct regdata *rdp = getregdata();
2251	const struct regdomain *rd;
2252
2253	rd = lib80211_regdomain_findbyname(rdp, val);
2254	if (rd == NULL) {
2255		char *eptr;
2256		long sku = strtol(val, &eptr, 0);
2257
2258		if (eptr != val)
2259			rd = lib80211_regdomain_findbysku(rdp, sku);
2260		if (eptr == val || rd == NULL)
2261			errx(1, "unknown regdomain %s", val);
2262	}
2263	getregdomain(s);
2264	regdomain.regdomain = rd->sku;
2265	if (regdomain.country == 0 && rd->cc != NULL) {
2266		/*
2267		 * No country code setup and there's a default
2268		 * one for this regdomain fill it in.
2269		 */
2270		defaultcountry(rd);
2271	}
2272	callback_register(setregdomain_cb, &regdomain);
2273}
2274
2275static
2276DECL_CMD_FUNC(set80211country, val, d)
2277{
2278	struct regdata *rdp = getregdata();
2279	const struct country *cc;
2280
2281	cc = lib80211_country_findbyname(rdp, val);
2282	if (cc == NULL) {
2283		char *eptr;
2284		long code = strtol(val, &eptr, 0);
2285
2286		if (eptr != val)
2287			cc = lib80211_country_findbycc(rdp, code);
2288		if (eptr == val || cc == NULL)
2289			errx(1, "unknown ISO country code %s", val);
2290	}
2291	getregdomain(s);
2292	regdomain.regdomain = cc->rd->sku;
2293	regdomain.country = cc->code;
2294	regdomain.isocc[0] = cc->isoname[0];
2295	regdomain.isocc[1] = cc->isoname[1];
2296	callback_register(setregdomain_cb, &regdomain);
2297}
2298
2299static void
2300set80211location(const char *val, int d, int s, const struct afswtch *rafp)
2301{
2302	getregdomain(s);
2303	regdomain.location = d;
2304	callback_register(setregdomain_cb, &regdomain);
2305}
2306
2307static void
2308set80211ecm(const char *val, int d, int s, const struct afswtch *rafp)
2309{
2310	getregdomain(s);
2311	regdomain.ecm = d;
2312	callback_register(setregdomain_cb, &regdomain);
2313}
2314
2315static void
2316LINE_INIT(char c)
2317{
2318	spacer = c;
2319	if (c == '\t')
2320		col = 8;
2321	else
2322		col = 1;
2323}
2324
2325static void
2326LINE_BREAK(void)
2327{
2328	if (spacer != '\t') {
2329		printf("\n");
2330		spacer = '\t';
2331	}
2332	col = 8;		/* 8-col tab */
2333}
2334
2335static void
2336LINE_CHECK(const char *fmt, ...)
2337{
2338	char buf[80];
2339	va_list ap;
2340	int n;
2341
2342	va_start(ap, fmt);
2343	n = vsnprintf(buf+1, sizeof(buf)-1, fmt, ap);
2344	va_end(ap);
2345	col += 1+n;
2346	if (col > MAXCOL) {
2347		LINE_BREAK();
2348		col += n;
2349	}
2350	buf[0] = spacer;
2351	printf("%s", buf);
2352	spacer = ' ';
2353}
2354
2355static int
2356getmaxrate(const uint8_t rates[15], uint8_t nrates)
2357{
2358	int i, maxrate = -1;
2359
2360	for (i = 0; i < nrates; i++) {
2361		int rate = rates[i] & IEEE80211_RATE_VAL;
2362		if (rate > maxrate)
2363			maxrate = rate;
2364	}
2365	return maxrate / 2;
2366}
2367
2368static const char *
2369getcaps(int capinfo)
2370{
2371	static char capstring[32];
2372	char *cp = capstring;
2373
2374	if (capinfo & IEEE80211_CAPINFO_ESS)
2375		*cp++ = 'E';
2376	if (capinfo & IEEE80211_CAPINFO_IBSS)
2377		*cp++ = 'I';
2378	if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
2379		*cp++ = 'c';
2380	if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
2381		*cp++ = 'C';
2382	if (capinfo & IEEE80211_CAPINFO_PRIVACY)
2383		*cp++ = 'P';
2384	if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
2385		*cp++ = 'S';
2386	if (capinfo & IEEE80211_CAPINFO_PBCC)
2387		*cp++ = 'B';
2388	if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
2389		*cp++ = 'A';
2390	if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
2391		*cp++ = 's';
2392	if (capinfo & IEEE80211_CAPINFO_RSN)
2393		*cp++ = 'R';
2394	if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
2395		*cp++ = 'D';
2396	*cp = '\0';
2397	return capstring;
2398}
2399
2400static const char *
2401getflags(int flags)
2402{
2403	static char flagstring[32];
2404	char *cp = flagstring;
2405
2406	if (flags & IEEE80211_NODE_AUTH)
2407		*cp++ = 'A';
2408	if (flags & IEEE80211_NODE_QOS)
2409		*cp++ = 'Q';
2410	if (flags & IEEE80211_NODE_ERP)
2411		*cp++ = 'E';
2412	if (flags & IEEE80211_NODE_PWR_MGT)
2413		*cp++ = 'P';
2414	if (flags & IEEE80211_NODE_HT) {
2415		*cp++ = 'H';
2416		if (flags & IEEE80211_NODE_HTCOMPAT)
2417			*cp++ = '+';
2418	}
2419	if (flags & IEEE80211_NODE_WPS)
2420		*cp++ = 'W';
2421	if (flags & IEEE80211_NODE_TSN)
2422		*cp++ = 'N';
2423	if (flags & IEEE80211_NODE_AMPDU_TX)
2424		*cp++ = 'T';
2425	if (flags & IEEE80211_NODE_AMPDU_RX)
2426		*cp++ = 'R';
2427	if (flags & IEEE80211_NODE_MIMO_PS) {
2428		*cp++ = 'M';
2429		if (flags & IEEE80211_NODE_MIMO_RTS)
2430			*cp++ = '+';
2431	}
2432	if (flags & IEEE80211_NODE_RIFS)
2433		*cp++ = 'I';
2434	if (flags & IEEE80211_NODE_SGI40) {
2435		*cp++ = 'S';
2436		if (flags & IEEE80211_NODE_SGI20)
2437			*cp++ = '+';
2438	} else if (flags & IEEE80211_NODE_SGI20)
2439		*cp++ = 's';
2440	if (flags & IEEE80211_NODE_AMSDU_TX)
2441		*cp++ = 't';
2442	if (flags & IEEE80211_NODE_AMSDU_RX)
2443		*cp++ = 'r';
2444	*cp = '\0';
2445	return flagstring;
2446}
2447
2448static void
2449printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
2450{
2451	printf("%s", tag);
2452	if (verbose) {
2453		maxlen -= strlen(tag)+2;
2454		if (2*ielen > maxlen)
2455			maxlen--;
2456		printf("<");
2457		for (; ielen > 0; ie++, ielen--) {
2458			if (maxlen-- <= 0)
2459				break;
2460			printf("%02x", *ie);
2461		}
2462		if (ielen != 0)
2463			printf("-");
2464		printf(">");
2465	}
2466}
2467
2468#define LE_READ_2(p)					\
2469	((u_int16_t)					\
2470	 ((((const u_int8_t *)(p))[0]      ) |		\
2471	  (((const u_int8_t *)(p))[1] <<  8)))
2472#define LE_READ_4(p)					\
2473	((u_int32_t)					\
2474	 ((((const u_int8_t *)(p))[0]      ) |		\
2475	  (((const u_int8_t *)(p))[1] <<  8) |		\
2476	  (((const u_int8_t *)(p))[2] << 16) |		\
2477	  (((const u_int8_t *)(p))[3] << 24)))
2478
2479/*
2480 * NB: The decoding routines assume a properly formatted ie
2481 *     which should be safe as the kernel only retains them
2482 *     if they parse ok.
2483 */
2484
2485static void
2486printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2487{
2488#define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
2489	static const char *acnames[] = { "BE", "BK", "VO", "VI" };
2490	const struct ieee80211_wme_param *wme =
2491	    (const struct ieee80211_wme_param *) ie;
2492	int i;
2493
2494	printf("%s", tag);
2495	if (!verbose)
2496		return;
2497	printf("<qosinfo 0x%x", wme->param_qosInfo);
2498	ie += offsetof(struct ieee80211_wme_param, params_acParams);
2499	for (i = 0; i < WME_NUM_AC; i++) {
2500		const struct ieee80211_wme_acparams *ac =
2501		    &wme->params_acParams[i];
2502
2503		printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
2504			, acnames[i]
2505			, MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
2506			, MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
2507			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
2508			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
2509			, LE_READ_2(&ac->acp_txop)
2510		);
2511	}
2512	printf(">");
2513#undef MS
2514}
2515
2516static void
2517printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2518{
2519	printf("%s", tag);
2520	if (verbose) {
2521		const struct ieee80211_wme_info *wme =
2522		    (const struct ieee80211_wme_info *) ie;
2523		printf("<version 0x%x info 0x%x>",
2524		    wme->wme_version, wme->wme_info);
2525	}
2526}
2527
2528static void
2529printhtcap(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2530{
2531	printf("%s", tag);
2532	if (verbose) {
2533		const struct ieee80211_ie_htcap *htcap =
2534		    (const struct ieee80211_ie_htcap *) ie;
2535		const char *sep;
2536		int i, j;
2537
2538		printf("<cap 0x%x param 0x%x",
2539		    LE_READ_2(&htcap->hc_cap), htcap->hc_param);
2540		printf(" mcsset[");
2541		sep = "";
2542		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2543			if (isset(htcap->hc_mcsset, i)) {
2544				for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2545					if (isclr(htcap->hc_mcsset, j))
2546						break;
2547				j--;
2548				if (i == j)
2549					printf("%s%u", sep, i);
2550				else
2551					printf("%s%u-%u", sep, i, j);
2552				i += j-i;
2553				sep = ",";
2554			}
2555		printf("] extcap 0x%x txbf 0x%x antenna 0x%x>",
2556		    LE_READ_2(&htcap->hc_extcap),
2557		    LE_READ_4(&htcap->hc_txbf),
2558		    htcap->hc_antenna);
2559	}
2560}
2561
2562static void
2563printhtinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2564{
2565	printf("%s", tag);
2566	if (verbose) {
2567		const struct ieee80211_ie_htinfo *htinfo =
2568		    (const struct ieee80211_ie_htinfo *) ie;
2569		const char *sep;
2570		int i, j;
2571
2572		printf("<ctl %u, %x,%x,%x,%x", htinfo->hi_ctrlchannel,
2573		    htinfo->hi_byte1, htinfo->hi_byte2, htinfo->hi_byte3,
2574		    LE_READ_2(&htinfo->hi_byte45));
2575		printf(" basicmcs[");
2576		sep = "";
2577		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2578			if (isset(htinfo->hi_basicmcsset, i)) {
2579				for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2580					if (isclr(htinfo->hi_basicmcsset, j))
2581						break;
2582				j--;
2583				if (i == j)
2584					printf("%s%u", sep, i);
2585				else
2586					printf("%s%u-%u", sep, i, j);
2587				i += j-i;
2588				sep = ",";
2589			}
2590		printf("]>");
2591	}
2592}
2593
2594static void
2595printathie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2596{
2597
2598	printf("%s", tag);
2599	if (verbose) {
2600		const struct ieee80211_ath_ie *ath =
2601			(const struct ieee80211_ath_ie *)ie;
2602
2603		printf("<");
2604		if (ath->ath_capability & ATHEROS_CAP_TURBO_PRIME)
2605			printf("DTURBO,");
2606		if (ath->ath_capability & ATHEROS_CAP_COMPRESSION)
2607			printf("COMP,");
2608		if (ath->ath_capability & ATHEROS_CAP_FAST_FRAME)
2609			printf("FF,");
2610		if (ath->ath_capability & ATHEROS_CAP_XR)
2611			printf("XR,");
2612		if (ath->ath_capability & ATHEROS_CAP_AR)
2613			printf("AR,");
2614		if (ath->ath_capability & ATHEROS_CAP_BURST)
2615			printf("BURST,");
2616		if (ath->ath_capability & ATHEROS_CAP_WME)
2617			printf("WME,");
2618		if (ath->ath_capability & ATHEROS_CAP_BOOST)
2619			printf("BOOST,");
2620		printf("0x%x>", LE_READ_2(ath->ath_defkeyix));
2621	}
2622}
2623
2624
2625static void
2626printmeshconf(const char *tag, const uint8_t *ie, size_t ielen, int maxlen)
2627{
2628#define MATCHOUI(field, oui, string)					\
2629do {									\
2630	if (memcmp(field, oui, 4) == 0)					\
2631		printf("%s", string);					\
2632} while (0)
2633
2634	printf("%s", tag);
2635	if (verbose) {
2636		const struct ieee80211_meshconf_ie *mconf =
2637			(const struct ieee80211_meshconf_ie *)ie;
2638		printf("<PATH:");
2639		if (mconf->conf_pselid == IEEE80211_MESHCONF_PATH_HWMP)
2640			printf("HWMP");
2641		else
2642			printf("UNKNOWN");
2643		printf(" LINK:");
2644		if (mconf->conf_pmetid == IEEE80211_MESHCONF_METRIC_AIRTIME)
2645			printf("AIRTIME");
2646		else
2647			printf("UNKNOWN");
2648		printf(" CONGESTION:");
2649		if (mconf->conf_ccid == IEEE80211_MESHCONF_CC_DISABLED)
2650			printf("DISABLED");
2651		else
2652			printf("UNKNOWN");
2653		printf(" SYNC:");
2654		if (mconf->conf_syncid == IEEE80211_MESHCONF_SYNC_NEIGHOFF)
2655			printf("NEIGHOFF");
2656		else
2657			printf("UNKNOWN");
2658		printf(" AUTH:");
2659		if (mconf->conf_authid == IEEE80211_MESHCONF_AUTH_DISABLED)
2660			printf("DISABLED");
2661		else
2662			printf("UNKNOWN");
2663		printf(" FORM:0x%x CAPS:0x%x>", mconf->conf_form,
2664		    mconf->conf_cap);
2665	}
2666#undef MATCHOUI
2667}
2668
2669static const char *
2670wpa_cipher(const u_int8_t *sel)
2671{
2672#define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
2673	u_int32_t w = LE_READ_4(sel);
2674
2675	switch (w) {
2676	case WPA_SEL(WPA_CSE_NULL):
2677		return "NONE";
2678	case WPA_SEL(WPA_CSE_WEP40):
2679		return "WEP40";
2680	case WPA_SEL(WPA_CSE_WEP104):
2681		return "WEP104";
2682	case WPA_SEL(WPA_CSE_TKIP):
2683		return "TKIP";
2684	case WPA_SEL(WPA_CSE_CCMP):
2685		return "AES-CCMP";
2686	}
2687	return "?";		/* NB: so 1<< is discarded */
2688#undef WPA_SEL
2689}
2690
2691static const char *
2692wpa_keymgmt(const u_int8_t *sel)
2693{
2694#define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
2695	u_int32_t w = LE_READ_4(sel);
2696
2697	switch (w) {
2698	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
2699		return "8021X-UNSPEC";
2700	case WPA_SEL(WPA_ASE_8021X_PSK):
2701		return "8021X-PSK";
2702	case WPA_SEL(WPA_ASE_NONE):
2703		return "NONE";
2704	}
2705	return "?";
2706#undef WPA_SEL
2707}
2708
2709static void
2710printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2711{
2712	u_int8_t len = ie[1];
2713
2714	printf("%s", tag);
2715	if (verbose) {
2716		const char *sep;
2717		int n;
2718
2719		ie += 6, len -= 4;		/* NB: len is payload only */
2720
2721		printf("<v%u", LE_READ_2(ie));
2722		ie += 2, len -= 2;
2723
2724		printf(" mc:%s", wpa_cipher(ie));
2725		ie += 4, len -= 4;
2726
2727		/* unicast ciphers */
2728		n = LE_READ_2(ie);
2729		ie += 2, len -= 2;
2730		sep = " uc:";
2731		for (; n > 0; n--) {
2732			printf("%s%s", sep, wpa_cipher(ie));
2733			ie += 4, len -= 4;
2734			sep = "+";
2735		}
2736
2737		/* key management algorithms */
2738		n = LE_READ_2(ie);
2739		ie += 2, len -= 2;
2740		sep = " km:";
2741		for (; n > 0; n--) {
2742			printf("%s%s", sep, wpa_keymgmt(ie));
2743			ie += 4, len -= 4;
2744			sep = "+";
2745		}
2746
2747		if (len > 2)		/* optional capabilities */
2748			printf(", caps 0x%x", LE_READ_2(ie));
2749		printf(">");
2750	}
2751}
2752
2753static const char *
2754rsn_cipher(const u_int8_t *sel)
2755{
2756#define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
2757	u_int32_t w = LE_READ_4(sel);
2758
2759	switch (w) {
2760	case RSN_SEL(RSN_CSE_NULL):
2761		return "NONE";
2762	case RSN_SEL(RSN_CSE_WEP40):
2763		return "WEP40";
2764	case RSN_SEL(RSN_CSE_WEP104):
2765		return "WEP104";
2766	case RSN_SEL(RSN_CSE_TKIP):
2767		return "TKIP";
2768	case RSN_SEL(RSN_CSE_CCMP):
2769		return "AES-CCMP";
2770	case RSN_SEL(RSN_CSE_WRAP):
2771		return "AES-OCB";
2772	}
2773	return "?";
2774#undef WPA_SEL
2775}
2776
2777static const char *
2778rsn_keymgmt(const u_int8_t *sel)
2779{
2780#define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
2781	u_int32_t w = LE_READ_4(sel);
2782
2783	switch (w) {
2784	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
2785		return "8021X-UNSPEC";
2786	case RSN_SEL(RSN_ASE_8021X_PSK):
2787		return "8021X-PSK";
2788	case RSN_SEL(RSN_ASE_NONE):
2789		return "NONE";
2790	}
2791	return "?";
2792#undef RSN_SEL
2793}
2794
2795static void
2796printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2797{
2798	printf("%s", tag);
2799	if (verbose) {
2800		const char *sep;
2801		int n;
2802
2803		ie += 2, ielen -= 2;
2804
2805		printf("<v%u", LE_READ_2(ie));
2806		ie += 2, ielen -= 2;
2807
2808		printf(" mc:%s", rsn_cipher(ie));
2809		ie += 4, ielen -= 4;
2810
2811		/* unicast ciphers */
2812		n = LE_READ_2(ie);
2813		ie += 2, ielen -= 2;
2814		sep = " uc:";
2815		for (; n > 0; n--) {
2816			printf("%s%s", sep, rsn_cipher(ie));
2817			ie += 4, ielen -= 4;
2818			sep = "+";
2819		}
2820
2821		/* key management algorithms */
2822		n = LE_READ_2(ie);
2823		ie += 2, ielen -= 2;
2824		sep = " km:";
2825		for (; n > 0; n--) {
2826			printf("%s%s", sep, rsn_keymgmt(ie));
2827			ie += 4, ielen -= 4;
2828			sep = "+";
2829		}
2830
2831		if (ielen > 2)		/* optional capabilities */
2832			printf(", caps 0x%x", LE_READ_2(ie));
2833		/* XXXPMKID */
2834		printf(">");
2835	}
2836}
2837
2838/* XXX move to a public include file */
2839#define IEEE80211_WPS_DEV_PASS_ID	0x1012
2840#define IEEE80211_WPS_SELECTED_REG	0x1041
2841#define IEEE80211_WPS_SETUP_STATE	0x1044
2842#define IEEE80211_WPS_UUID_E		0x1047
2843#define IEEE80211_WPS_VERSION		0x104a
2844
2845#define BE_READ_2(p)					\
2846	((u_int16_t)					\
2847	 ((((const u_int8_t *)(p))[1]      ) |		\
2848	  (((const u_int8_t *)(p))[0] <<  8)))
2849
2850static void
2851printwpsie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2852{
2853#define	N(a)	(sizeof(a) / sizeof(a[0]))
2854	u_int8_t len = ie[1];
2855
2856	printf("%s", tag);
2857	if (verbose) {
2858		static const char *dev_pass_id[] = {
2859			"D",	/* Default (PIN) */
2860			"U",	/* User-specified */
2861			"M",	/* Machine-specified */
2862			"K",	/* Rekey */
2863			"P",	/* PushButton */
2864			"R"	/* Registrar-specified */
2865		};
2866		int n;
2867
2868		ie +=6, len -= 4;		/* NB: len is payload only */
2869
2870		/* WPS IE in Beacon and Probe Resp frames have different fields */
2871		printf("<");
2872		while (len) {
2873			uint16_t tlv_type = BE_READ_2(ie);
2874			uint16_t tlv_len  = BE_READ_2(ie + 2);
2875
2876			ie += 4, len -= 4;
2877
2878			switch (tlv_type) {
2879			case IEEE80211_WPS_VERSION:
2880				printf("v:%d.%d", *ie >> 4, *ie & 0xf);
2881				break;
2882			case IEEE80211_WPS_SETUP_STATE:
2883				/* Only 1 and 2 are valid */
2884				if (*ie == 0 || *ie >= 3)
2885					printf(" state:B");
2886				else
2887					printf(" st:%s", *ie == 1 ? "N" : "C");
2888				break;
2889			case IEEE80211_WPS_SELECTED_REG:
2890				printf(" sel:%s", *ie ? "T" : "F");
2891				break;
2892			case IEEE80211_WPS_DEV_PASS_ID:
2893				n = LE_READ_2(ie);
2894				if (n < N(dev_pass_id))
2895					printf(" dpi:%s", dev_pass_id[n]);
2896				break;
2897			case IEEE80211_WPS_UUID_E:
2898				printf(" uuid-e:");
2899				for (n = 0; n < (tlv_len - 1); n++)
2900					printf("%02x-", ie[n]);
2901				printf("%02x", ie[n]);
2902				break;
2903			}
2904			ie += tlv_len, len -= tlv_len;
2905		}
2906		printf(">");
2907	}
2908#undef N
2909}
2910
2911static void
2912printtdmaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2913{
2914	printf("%s", tag);
2915	if (verbose && ielen >= sizeof(struct ieee80211_tdma_param)) {
2916		const struct ieee80211_tdma_param *tdma =
2917		   (const struct ieee80211_tdma_param *) ie;
2918
2919		/* XXX tstamp */
2920		printf("<v%u slot:%u slotcnt:%u slotlen:%u bintval:%u inuse:0x%x>",
2921		    tdma->tdma_version, tdma->tdma_slot, tdma->tdma_slotcnt,
2922		    LE_READ_2(&tdma->tdma_slotlen), tdma->tdma_bintval,
2923		    tdma->tdma_inuse[0]);
2924	}
2925}
2926
2927/*
2928 * Copy the ssid string contents into buf, truncating to fit.  If the
2929 * ssid is entirely printable then just copy intact.  Otherwise convert
2930 * to hexadecimal.  If the result is truncated then replace the last
2931 * three characters with "...".
2932 */
2933static int
2934copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
2935{
2936	const u_int8_t *p;
2937	size_t maxlen;
2938	int i;
2939
2940	if (essid_len > bufsize)
2941		maxlen = bufsize;
2942	else
2943		maxlen = essid_len;
2944	/* determine printable or not */
2945	for (i = 0, p = essid; i < maxlen; i++, p++) {
2946		if (*p < ' ' || *p > 0x7e)
2947			break;
2948	}
2949	if (i != maxlen) {		/* not printable, print as hex */
2950		if (bufsize < 3)
2951			return 0;
2952		strlcpy(buf, "0x", bufsize);
2953		bufsize -= 2;
2954		p = essid;
2955		for (i = 0; i < maxlen && bufsize >= 2; i++) {
2956			sprintf(&buf[2+2*i], "%02x", p[i]);
2957			bufsize -= 2;
2958		}
2959		if (i != essid_len)
2960			memcpy(&buf[2+2*i-3], "...", 3);
2961	} else {			/* printable, truncate as needed */
2962		memcpy(buf, essid, maxlen);
2963		if (maxlen != essid_len)
2964			memcpy(&buf[maxlen-3], "...", 3);
2965	}
2966	return maxlen;
2967}
2968
2969static void
2970printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2971{
2972	char ssid[2*IEEE80211_NWID_LEN+1];
2973
2974	printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
2975}
2976
2977static void
2978printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2979{
2980	const char *sep;
2981	int i;
2982
2983	printf("%s", tag);
2984	sep = "<";
2985	for (i = 2; i < ielen; i++) {
2986		printf("%s%s%d", sep,
2987		    ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
2988		    ie[i] & IEEE80211_RATE_VAL);
2989		sep = ",";
2990	}
2991	printf(">");
2992}
2993
2994static void
2995printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2996{
2997	const struct ieee80211_country_ie *cie =
2998	   (const struct ieee80211_country_ie *) ie;
2999	int i, nbands, schan, nchan;
3000
3001	printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
3002	nbands = (cie->len - 3) / sizeof(cie->band[0]);
3003	for (i = 0; i < nbands; i++) {
3004		schan = cie->band[i].schan;
3005		nchan = cie->band[i].nchan;
3006		if (nchan != 1)
3007			printf(" %u-%u,%u", schan, schan + nchan-1,
3008			    cie->band[i].maxtxpwr);
3009		else
3010			printf(" %u,%u", schan, cie->band[i].maxtxpwr);
3011	}
3012	printf(">");
3013}
3014
3015/* unaligned little endian access */
3016#define LE_READ_4(p)					\
3017	((u_int32_t)					\
3018	 ((((const u_int8_t *)(p))[0]      ) |		\
3019	  (((const u_int8_t *)(p))[1] <<  8) |		\
3020	  (((const u_int8_t *)(p))[2] << 16) |		\
3021	  (((const u_int8_t *)(p))[3] << 24)))
3022
3023static __inline int
3024iswpaoui(const u_int8_t *frm)
3025{
3026	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
3027}
3028
3029static __inline int
3030iswmeinfo(const u_int8_t *frm)
3031{
3032	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
3033		frm[6] == WME_INFO_OUI_SUBTYPE;
3034}
3035
3036static __inline int
3037iswmeparam(const u_int8_t *frm)
3038{
3039	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
3040		frm[6] == WME_PARAM_OUI_SUBTYPE;
3041}
3042
3043static __inline int
3044isatherosoui(const u_int8_t *frm)
3045{
3046	return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
3047}
3048
3049static __inline int
3050istdmaoui(const uint8_t *frm)
3051{
3052	return frm[1] > 3 && LE_READ_4(frm+2) == ((TDMA_OUI_TYPE<<24)|TDMA_OUI);
3053}
3054
3055static __inline int
3056iswpsoui(const uint8_t *frm)
3057{
3058	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPS_OUI_TYPE<<24)|WPA_OUI);
3059}
3060
3061static const char *
3062iename(int elemid)
3063{
3064	switch (elemid) {
3065	case IEEE80211_ELEMID_FHPARMS:	return " FHPARMS";
3066	case IEEE80211_ELEMID_CFPARMS:	return " CFPARMS";
3067	case IEEE80211_ELEMID_TIM:	return " TIM";
3068	case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
3069	case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
3070	case IEEE80211_ELEMID_PWRCNSTR:	return " PWRCNSTR";
3071	case IEEE80211_ELEMID_PWRCAP:	return " PWRCAP";
3072	case IEEE80211_ELEMID_TPCREQ:	return " TPCREQ";
3073	case IEEE80211_ELEMID_TPCREP:	return " TPCREP";
3074	case IEEE80211_ELEMID_SUPPCHAN:	return " SUPPCHAN";
3075	case IEEE80211_ELEMID_CSA:	return " CSA";
3076	case IEEE80211_ELEMID_MEASREQ:	return " MEASREQ";
3077	case IEEE80211_ELEMID_MEASREP:	return " MEASREP";
3078	case IEEE80211_ELEMID_QUIET:	return " QUIET";
3079	case IEEE80211_ELEMID_IBSSDFS:	return " IBSSDFS";
3080	case IEEE80211_ELEMID_TPC:	return " TPC";
3081	case IEEE80211_ELEMID_CCKM:	return " CCKM";
3082	}
3083	return " ???";
3084}
3085
3086static void
3087printies(const u_int8_t *vp, int ielen, int maxcols)
3088{
3089	while (ielen > 0) {
3090		switch (vp[0]) {
3091		case IEEE80211_ELEMID_SSID:
3092			if (verbose)
3093				printssid(" SSID", vp, 2+vp[1], maxcols);
3094			break;
3095		case IEEE80211_ELEMID_RATES:
3096		case IEEE80211_ELEMID_XRATES:
3097			if (verbose)
3098				printrates(vp[0] == IEEE80211_ELEMID_RATES ?
3099				    " RATES" : " XRATES", vp, 2+vp[1], maxcols);
3100			break;
3101		case IEEE80211_ELEMID_DSPARMS:
3102			if (verbose)
3103				printf(" DSPARMS<%u>", vp[2]);
3104			break;
3105		case IEEE80211_ELEMID_COUNTRY:
3106			if (verbose)
3107				printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
3108			break;
3109		case IEEE80211_ELEMID_ERP:
3110			if (verbose)
3111				printf(" ERP<0x%x>", vp[2]);
3112			break;
3113		case IEEE80211_ELEMID_VENDOR:
3114			if (iswpaoui(vp))
3115				printwpaie(" WPA", vp, 2+vp[1], maxcols);
3116			else if (iswmeinfo(vp))
3117				printwmeinfo(" WME", vp, 2+vp[1], maxcols);
3118			else if (iswmeparam(vp))
3119				printwmeparam(" WME", vp, 2+vp[1], maxcols);
3120			else if (isatherosoui(vp))
3121				printathie(" ATH", vp, 2+vp[1], maxcols);
3122			else if (iswpsoui(vp))
3123				printwpsie(" WPS", vp, 2+vp[1], maxcols);
3124			else if (istdmaoui(vp))
3125				printtdmaie(" TDMA", vp, 2+vp[1], maxcols);
3126			else if (verbose)
3127				printie(" VEN", vp, 2+vp[1], maxcols);
3128			break;
3129		case IEEE80211_ELEMID_RSN:
3130			printrsnie(" RSN", vp, 2+vp[1], maxcols);
3131			break;
3132		case IEEE80211_ELEMID_HTCAP:
3133			printhtcap(" HTCAP", vp, 2+vp[1], maxcols);
3134			break;
3135		case IEEE80211_ELEMID_HTINFO:
3136			if (verbose)
3137				printhtinfo(" HTINFO", vp, 2+vp[1], maxcols);
3138			break;
3139		case IEEE80211_ELEMID_MESHID:
3140			if (verbose)
3141				printssid(" MESHID", vp, 2+vp[1], maxcols);
3142			break;
3143		case IEEE80211_ELEMID_MESHCONF:
3144			printmeshconf(" MESHCONF", vp, 2+vp[1], maxcols);
3145			break;
3146		default:
3147			if (verbose)
3148				printie(iename(vp[0]), vp, 2+vp[1], maxcols);
3149			break;
3150		}
3151		ielen -= 2+vp[1];
3152		vp += 2+vp[1];
3153	}
3154}
3155
3156static void
3157printmimo(const struct ieee80211_mimo_info *mi)
3158{
3159	/* NB: don't muddy display unless there's something to show */
3160	if (mi->rssi[0] != 0 || mi->rssi[1] != 0 || mi->rssi[2] != 0) {
3161		/* XXX ignore EVM for now */
3162		printf(" (rssi %d:%d:%d nf %d:%d:%d)",
3163		    mi->rssi[0], mi->rssi[1], mi->rssi[2],
3164		    mi->noise[0], mi->noise[1], mi->noise[2]);
3165	}
3166}
3167
3168static void
3169list_scan(int s)
3170{
3171	uint8_t buf[24*1024];
3172	char ssid[IEEE80211_NWID_LEN+1];
3173	const uint8_t *cp;
3174	int len, ssidmax, idlen;
3175
3176	if (get80211len(s, IEEE80211_IOC_SCAN_RESULTS, buf, sizeof(buf), &len) < 0)
3177		errx(1, "unable to get scan results");
3178	if (len < sizeof(struct ieee80211req_scan_result))
3179		return;
3180
3181	getchaninfo(s);
3182
3183	ssidmax = verbose ? IEEE80211_NWID_LEN - 1 : 14;
3184	printf("%-*.*s  %-17.17s  %4s %4s  %-7s  %3s %4s\n"
3185		, ssidmax, ssidmax, "SSID/MESH ID"
3186		, "BSSID"
3187		, "CHAN"
3188		, "RATE"
3189		, " S:N"
3190		, "INT"
3191		, "CAPS"
3192	);
3193	cp = buf;
3194	do {
3195		const struct ieee80211req_scan_result *sr;
3196		const uint8_t *vp, *idp;
3197
3198		sr = (const struct ieee80211req_scan_result *) cp;
3199		vp = cp + sr->isr_ie_off;
3200		if (sr->isr_meshid_len) {
3201			idp = vp + sr->isr_ssid_len;
3202			idlen = sr->isr_meshid_len;
3203		} else {
3204			idp = vp;
3205			idlen = sr->isr_ssid_len;
3206		}
3207		printf("%-*.*s  %s  %3d  %3dM %3d:%-3d  %3d %-4.4s"
3208			, ssidmax
3209			  , copy_essid(ssid, ssidmax, idp, idlen)
3210			  , ssid
3211			, ether_ntoa((const struct ether_addr *) sr->isr_bssid)
3212			, ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
3213			, getmaxrate(sr->isr_rates, sr->isr_nrates)
3214			, (sr->isr_rssi/2)+sr->isr_noise, sr->isr_noise
3215			, sr->isr_intval
3216			, getcaps(sr->isr_capinfo)
3217		);
3218		printies(vp + sr->isr_ssid_len + sr->isr_meshid_len,
3219		    sr->isr_ie_len, 24);
3220		printf("\n");
3221		cp += sr->isr_len, len -= sr->isr_len;
3222	} while (len >= sizeof(struct ieee80211req_scan_result));
3223}
3224
3225static void
3226scan_and_wait(int s)
3227{
3228	struct ieee80211_scan_req sr;
3229	struct ieee80211req ireq;
3230	int sroute;
3231
3232	sroute = socket(PF_ROUTE, SOCK_RAW, 0);
3233	if (sroute < 0) {
3234		perror("socket(PF_ROUTE,SOCK_RAW)");
3235		return;
3236	}
3237	(void) memset(&ireq, 0, sizeof(ireq));
3238	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3239	ireq.i_type = IEEE80211_IOC_SCAN_REQ;
3240
3241	memset(&sr, 0, sizeof(sr));
3242	sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE
3243		    | IEEE80211_IOC_SCAN_BGSCAN
3244		    | IEEE80211_IOC_SCAN_NOPICK
3245		    | IEEE80211_IOC_SCAN_ONCE;
3246	sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
3247	sr.sr_nssid = 0;
3248
3249	ireq.i_data = &sr;
3250	ireq.i_len = sizeof(sr);
3251	/*
3252	 * NB: only root can trigger a scan so ignore errors. Also ignore
3253	 * possible errors from net80211, even if no new scan could be
3254	 * started there might still be a valid scan cache.
3255	 */
3256	if (ioctl(s, SIOCS80211, &ireq) == 0) {
3257		char buf[2048];
3258		struct if_announcemsghdr *ifan;
3259		struct rt_msghdr *rtm;
3260
3261		do {
3262			if (read(sroute, buf, sizeof(buf)) < 0) {
3263				perror("read(PF_ROUTE)");
3264				break;
3265			}
3266			rtm = (struct rt_msghdr *) buf;
3267			if (rtm->rtm_version != RTM_VERSION)
3268				break;
3269			ifan = (struct if_announcemsghdr *) rtm;
3270		} while (rtm->rtm_type != RTM_IEEE80211 ||
3271		    ifan->ifan_what != RTM_IEEE80211_SCAN);
3272	}
3273	close(sroute);
3274}
3275
3276static
3277DECL_CMD_FUNC(set80211scan, val, d)
3278{
3279	scan_and_wait(s);
3280	list_scan(s);
3281}
3282
3283static enum ieee80211_opmode get80211opmode(int s);
3284
3285static int
3286gettxseq(const struct ieee80211req_sta_info *si)
3287{
3288	int i, txseq;
3289
3290	if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3291		return si->isi_txseqs[0];
3292	/* XXX not right but usually what folks want */
3293	txseq = 0;
3294	for (i = 0; i < IEEE80211_TID_SIZE; i++)
3295		if (si->isi_txseqs[i] > txseq)
3296			txseq = si->isi_txseqs[i];
3297	return txseq;
3298}
3299
3300static int
3301getrxseq(const struct ieee80211req_sta_info *si)
3302{
3303	int i, rxseq;
3304
3305	if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3306		return si->isi_rxseqs[0];
3307	/* XXX not right but usually what folks want */
3308	rxseq = 0;
3309	for (i = 0; i < IEEE80211_TID_SIZE; i++)
3310		if (si->isi_rxseqs[i] > rxseq)
3311			rxseq = si->isi_rxseqs[i];
3312	return rxseq;
3313}
3314
3315static void
3316list_stations(int s)
3317{
3318	union {
3319		struct ieee80211req_sta_req req;
3320		uint8_t buf[24*1024];
3321	} u;
3322	enum ieee80211_opmode opmode = get80211opmode(s);
3323	const uint8_t *cp;
3324	int len;
3325
3326	/* broadcast address =>'s get all stations */
3327	(void) memset(u.req.is_u.macaddr, 0xff, IEEE80211_ADDR_LEN);
3328	if (opmode == IEEE80211_M_STA) {
3329		/*
3330		 * Get information about the associated AP.
3331		 */
3332		(void) get80211(s, IEEE80211_IOC_BSSID,
3333		    u.req.is_u.macaddr, IEEE80211_ADDR_LEN);
3334	}
3335	if (get80211len(s, IEEE80211_IOC_STA_INFO, &u, sizeof(u), &len) < 0)
3336		errx(1, "unable to get station information");
3337	if (len < sizeof(struct ieee80211req_sta_info))
3338		return;
3339
3340	getchaninfo(s);
3341
3342	if (opmode == IEEE80211_M_MBSS)
3343		printf("%-17.17s %4s %5s %5s %7s %4s %4s %4s %6s %6s\n"
3344			, "ADDR"
3345			, "CHAN"
3346			, "LOCAL"
3347			, "PEER"
3348			, "STATE"
3349			, "RATE"
3350			, "RSSI"
3351			, "IDLE"
3352			, "TXSEQ"
3353			, "RXSEQ"
3354		);
3355	else
3356		printf("%-17.17s %4s %4s %4s %4s %4s %6s %6s %4s %-7s\n"
3357			, "ADDR"
3358			, "AID"
3359			, "CHAN"
3360			, "RATE"
3361			, "RSSI"
3362			, "IDLE"
3363			, "TXSEQ"
3364			, "RXSEQ"
3365			, "CAPS"
3366			, "FLAG"
3367		);
3368	cp = (const uint8_t *) u.req.info;
3369	do {
3370		const struct ieee80211req_sta_info *si;
3371
3372		si = (const struct ieee80211req_sta_info *) cp;
3373		if (si->isi_len < sizeof(*si))
3374			break;
3375		if (opmode == IEEE80211_M_MBSS)
3376			printf("%s %4d %5x %5x %7.7s %3dM %4.1f %4d %6d %6d"
3377				, ether_ntoa((const struct ether_addr*)
3378				    si->isi_macaddr)
3379				, ieee80211_mhz2ieee(si->isi_freq,
3380				    si->isi_flags)
3381				, si->isi_localid
3382				, si->isi_peerid
3383				, mesh_linkstate_string(si->isi_peerstate)
3384				, si->isi_txmbps/2
3385				, si->isi_rssi/2.
3386				, si->isi_inact
3387				, gettxseq(si)
3388				, getrxseq(si)
3389			);
3390		else
3391			printf("%s %4u %4d %3dM %4.1f %4d %6d %6d %-4.4s %-7.7s"
3392				, ether_ntoa((const struct ether_addr*)
3393				    si->isi_macaddr)
3394				, IEEE80211_AID(si->isi_associd)
3395				, ieee80211_mhz2ieee(si->isi_freq,
3396				    si->isi_flags)
3397				, si->isi_txmbps/2
3398				, si->isi_rssi/2.
3399				, si->isi_inact
3400				, gettxseq(si)
3401				, getrxseq(si)
3402				, getcaps(si->isi_capinfo)
3403				, getflags(si->isi_state)
3404			);
3405		printies(cp + si->isi_ie_off, si->isi_ie_len, 24);
3406		printmimo(&si->isi_mimo);
3407		printf("\n");
3408		cp += si->isi_len, len -= si->isi_len;
3409	} while (len >= sizeof(struct ieee80211req_sta_info));
3410}
3411
3412static const char *
3413mesh_linkstate_string(uint8_t state)
3414{
3415#define	N(a)	(sizeof(a) / sizeof(a[0]))
3416	static const char *state_names[] = {
3417	    [0] = "IDLE",
3418	    [1] = "OPEN-TX",
3419	    [2] = "OPEN-RX",
3420	    [3] = "CONF-RX",
3421	    [4] = "ESTAB",
3422	    [5] = "HOLDING",
3423	};
3424
3425	if (state >= N(state_names)) {
3426		static char buf[10];
3427		snprintf(buf, sizeof(buf), "#%u", state);
3428		return buf;
3429	} else
3430		return state_names[state];
3431#undef N
3432}
3433
3434static const char *
3435get_chaninfo(const struct ieee80211_channel *c, int precise,
3436	char buf[], size_t bsize)
3437{
3438	buf[0] = '\0';
3439	if (IEEE80211_IS_CHAN_FHSS(c))
3440		strlcat(buf, " FHSS", bsize);
3441	if (IEEE80211_IS_CHAN_A(c))
3442		strlcat(buf, " 11a", bsize);
3443	else if (IEEE80211_IS_CHAN_ANYG(c))
3444		strlcat(buf, " 11g", bsize);
3445	else if (IEEE80211_IS_CHAN_B(c))
3446		strlcat(buf, " 11b", bsize);
3447	if (IEEE80211_IS_CHAN_HALF(c))
3448		strlcat(buf, "/10MHz", bsize);
3449	if (IEEE80211_IS_CHAN_QUARTER(c))
3450		strlcat(buf, "/5MHz", bsize);
3451	if (IEEE80211_IS_CHAN_TURBO(c))
3452		strlcat(buf, " Turbo", bsize);
3453	if (precise) {
3454		if (IEEE80211_IS_CHAN_HT20(c))
3455			strlcat(buf, " ht/20", bsize);
3456		else if (IEEE80211_IS_CHAN_HT40D(c))
3457			strlcat(buf, " ht/40-", bsize);
3458		else if (IEEE80211_IS_CHAN_HT40U(c))
3459			strlcat(buf, " ht/40+", bsize);
3460	} else {
3461		if (IEEE80211_IS_CHAN_HT(c))
3462			strlcat(buf, " ht", bsize);
3463	}
3464	return buf;
3465}
3466
3467static void
3468print_chaninfo(const struct ieee80211_channel *c, int verb)
3469{
3470	char buf[14];
3471
3472	if (verb)
3473		printf("Channel %3u : %u%c%c%c%c%c MHz%-14.14s",
3474		    ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3475		    IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3476		    IEEE80211_IS_CHAN_DFS(c) ? 'D' : ' ',
3477		    IEEE80211_IS_CHAN_RADAR(c) ? 'R' : ' ',
3478		    IEEE80211_IS_CHAN_CWINT(c) ? 'I' : ' ',
3479		    IEEE80211_IS_CHAN_CACDONE(c) ? 'C' : ' ',
3480		    get_chaninfo(c, verb, buf, sizeof(buf)));
3481	else
3482	printf("Channel %3u : %u%c MHz%-14.14s",
3483	    ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3484	    IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3485	    get_chaninfo(c, verb, buf, sizeof(buf)));
3486
3487}
3488
3489static int
3490chanpref(const struct ieee80211_channel *c)
3491{
3492	if (IEEE80211_IS_CHAN_HT40(c))
3493		return 40;
3494	if (IEEE80211_IS_CHAN_HT20(c))
3495		return 30;
3496	if (IEEE80211_IS_CHAN_HALF(c))
3497		return 10;
3498	if (IEEE80211_IS_CHAN_QUARTER(c))
3499		return 5;
3500	if (IEEE80211_IS_CHAN_TURBO(c))
3501		return 25;
3502	if (IEEE80211_IS_CHAN_A(c))
3503		return 20;
3504	if (IEEE80211_IS_CHAN_G(c))
3505		return 20;
3506	if (IEEE80211_IS_CHAN_B(c))
3507		return 15;
3508	if (IEEE80211_IS_CHAN_PUREG(c))
3509		return 15;
3510	return 0;
3511}
3512
3513static void
3514print_channels(int s, const struct ieee80211req_chaninfo *chans,
3515	int allchans, int verb)
3516{
3517	struct ieee80211req_chaninfo *achans;
3518	uint8_t reported[IEEE80211_CHAN_BYTES];
3519	const struct ieee80211_channel *c;
3520	int i, half;
3521
3522	achans = malloc(IEEE80211_CHANINFO_SPACE(chans));
3523	if (achans == NULL)
3524		errx(1, "no space for active channel list");
3525	achans->ic_nchans = 0;
3526	memset(reported, 0, sizeof(reported));
3527	if (!allchans) {
3528		struct ieee80211req_chanlist active;
3529
3530		if (get80211(s, IEEE80211_IOC_CHANLIST, &active, sizeof(active)) < 0)
3531			errx(1, "unable to get active channel list");
3532		for (i = 0; i < chans->ic_nchans; i++) {
3533			c = &chans->ic_chans[i];
3534			if (!isset(active.ic_channels, c->ic_ieee))
3535				continue;
3536			/*
3537			 * Suppress compatible duplicates unless
3538			 * verbose.  The kernel gives us it's
3539			 * complete channel list which has separate
3540			 * entries for 11g/11b and 11a/turbo.
3541			 */
3542			if (isset(reported, c->ic_ieee) && !verb) {
3543				/* XXX we assume duplicates are adjacent */
3544				achans->ic_chans[achans->ic_nchans-1] = *c;
3545			} else {
3546				achans->ic_chans[achans->ic_nchans++] = *c;
3547				setbit(reported, c->ic_ieee);
3548			}
3549		}
3550	} else {
3551		for (i = 0; i < chans->ic_nchans; i++) {
3552			c = &chans->ic_chans[i];
3553			/* suppress duplicates as above */
3554			if (isset(reported, c->ic_ieee) && !verb) {
3555				/* XXX we assume duplicates are adjacent */
3556				struct ieee80211_channel *a =
3557				    &achans->ic_chans[achans->ic_nchans-1];
3558				if (chanpref(c) > chanpref(a))
3559					*a = *c;
3560			} else {
3561				achans->ic_chans[achans->ic_nchans++] = *c;
3562				setbit(reported, c->ic_ieee);
3563			}
3564		}
3565	}
3566	half = achans->ic_nchans / 2;
3567	if (achans->ic_nchans % 2)
3568		half++;
3569
3570	for (i = 0; i < achans->ic_nchans / 2; i++) {
3571		print_chaninfo(&achans->ic_chans[i], verb);
3572		print_chaninfo(&achans->ic_chans[half+i], verb);
3573		printf("\n");
3574	}
3575	if (achans->ic_nchans % 2) {
3576		print_chaninfo(&achans->ic_chans[i], verb);
3577		printf("\n");
3578	}
3579	free(achans);
3580}
3581
3582static void
3583list_channels(int s, int allchans)
3584{
3585	getchaninfo(s);
3586	print_channels(s, chaninfo, allchans, verbose);
3587}
3588
3589static void
3590print_txpow(const struct ieee80211_channel *c)
3591{
3592	printf("Channel %3u : %u MHz %3.1f reg %2d  ",
3593	    c->ic_ieee, c->ic_freq,
3594	    c->ic_maxpower/2., c->ic_maxregpower);
3595}
3596
3597static void
3598print_txpow_verbose(const struct ieee80211_channel *c)
3599{
3600	print_chaninfo(c, 1);
3601	printf("min %4.1f dBm  max %3.1f dBm  reg %2d dBm",
3602	    c->ic_minpower/2., c->ic_maxpower/2., c->ic_maxregpower);
3603	/* indicate where regulatory cap limits power use */
3604	if (c->ic_maxpower > 2*c->ic_maxregpower)
3605		printf(" <");
3606}
3607
3608static void
3609list_txpow(int s)
3610{
3611	struct ieee80211req_chaninfo *achans;
3612	uint8_t reported[IEEE80211_CHAN_BYTES];
3613	struct ieee80211_channel *c, *prev;
3614	int i, half;
3615
3616	getchaninfo(s);
3617	achans = malloc(IEEE80211_CHANINFO_SPACE(chaninfo));
3618	if (achans == NULL)
3619		errx(1, "no space for active channel list");
3620	achans->ic_nchans = 0;
3621	memset(reported, 0, sizeof(reported));
3622	for (i = 0; i < chaninfo->ic_nchans; i++) {
3623		c = &chaninfo->ic_chans[i];
3624		/* suppress duplicates as above */
3625		if (isset(reported, c->ic_ieee) && !verbose) {
3626			/* XXX we assume duplicates are adjacent */
3627			prev = &achans->ic_chans[achans->ic_nchans-1];
3628			/* display highest power on channel */
3629			if (c->ic_maxpower > prev->ic_maxpower)
3630				*prev = *c;
3631		} else {
3632			achans->ic_chans[achans->ic_nchans++] = *c;
3633			setbit(reported, c->ic_ieee);
3634		}
3635	}
3636	if (!verbose) {
3637		half = achans->ic_nchans / 2;
3638		if (achans->ic_nchans % 2)
3639			half++;
3640
3641		for (i = 0; i < achans->ic_nchans / 2; i++) {
3642			print_txpow(&achans->ic_chans[i]);
3643			print_txpow(&achans->ic_chans[half+i]);
3644			printf("\n");
3645		}
3646		if (achans->ic_nchans % 2) {
3647			print_txpow(&achans->ic_chans[i]);
3648			printf("\n");
3649		}
3650	} else {
3651		for (i = 0; i < achans->ic_nchans; i++) {
3652			print_txpow_verbose(&achans->ic_chans[i]);
3653			printf("\n");
3654		}
3655	}
3656	free(achans);
3657}
3658
3659static void
3660list_keys(int s)
3661{
3662}
3663
3664#define	IEEE80211_C_BITS \
3665	"\20\1STA\002803ENCAP\7FF\10TURBOP\11IBSS\12PMGT" \
3666	"\13HOSTAP\14AHDEMO\15SWRETRY\16TXPMGT\17SHSLOT\20SHPREAMBLE" \
3667	"\21MONITOR\22DFS\23MBSS\30WPA1\31WPA2\32BURST\33WME\34WDS\36BGSCAN" \
3668	"\37TXFRAG\40TDMA"
3669
3670static void
3671list_capabilities(int s)
3672{
3673	struct ieee80211_devcaps_req *dc;
3674
3675	if (verbose)
3676		dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
3677	else
3678		dc = malloc(IEEE80211_DEVCAPS_SIZE(1));
3679	if (dc == NULL)
3680		errx(1, "no space for device capabilities");
3681	dc->dc_chaninfo.ic_nchans = verbose ? MAXCHAN : 1;
3682	getdevcaps(s, dc);
3683	printb("drivercaps", dc->dc_drivercaps, IEEE80211_C_BITS);
3684	if (dc->dc_cryptocaps != 0 || verbose) {
3685		putchar('\n');
3686		printb("cryptocaps", dc->dc_cryptocaps, IEEE80211_CRYPTO_BITS);
3687	}
3688	if (dc->dc_htcaps != 0 || verbose) {
3689		putchar('\n');
3690		printb("htcaps", dc->dc_htcaps, IEEE80211_HTCAP_BITS);
3691	}
3692	putchar('\n');
3693	if (verbose) {
3694		chaninfo = &dc->dc_chaninfo;	/* XXX */
3695		print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, verbose);
3696	}
3697	free(dc);
3698}
3699
3700static int
3701get80211wme(int s, int param, int ac, int *val)
3702{
3703	struct ieee80211req ireq;
3704
3705	(void) memset(&ireq, 0, sizeof(ireq));
3706	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3707	ireq.i_type = param;
3708	ireq.i_len = ac;
3709	if (ioctl(s, SIOCG80211, &ireq) < 0) {
3710		warn("cannot get WME parameter %d, ac %d%s",
3711		    param, ac & IEEE80211_WMEPARAM_VAL,
3712		    ac & IEEE80211_WMEPARAM_BSS ? " (BSS)" : "");
3713		return -1;
3714	}
3715	*val = ireq.i_val;
3716	return 0;
3717}
3718
3719static void
3720list_wme_aci(int s, const char *tag, int ac)
3721{
3722	int val;
3723
3724	printf("\t%s", tag);
3725
3726	/* show WME BSS parameters */
3727	if (get80211wme(s, IEEE80211_IOC_WME_CWMIN, ac, &val) != -1)
3728		printf(" cwmin %2u", val);
3729	if (get80211wme(s, IEEE80211_IOC_WME_CWMAX, ac, &val) != -1)
3730		printf(" cwmax %2u", val);
3731	if (get80211wme(s, IEEE80211_IOC_WME_AIFS, ac, &val) != -1)
3732		printf(" aifs %2u", val);
3733	if (get80211wme(s, IEEE80211_IOC_WME_TXOPLIMIT, ac, &val) != -1)
3734		printf(" txopLimit %3u", val);
3735	if (get80211wme(s, IEEE80211_IOC_WME_ACM, ac, &val) != -1) {
3736		if (val)
3737			printf(" acm");
3738		else if (verbose)
3739			printf(" -acm");
3740	}
3741	/* !BSS only */
3742	if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
3743		if (get80211wme(s, IEEE80211_IOC_WME_ACKPOLICY, ac, &val) != -1) {
3744			if (!val)
3745				printf(" -ack");
3746			else if (verbose)
3747				printf(" ack");
3748		}
3749	}
3750	printf("\n");
3751}
3752
3753static void
3754list_wme(int s)
3755{
3756	static const char *acnames[] = { "AC_BE", "AC_BK", "AC_VI", "AC_VO" };
3757	int ac;
3758
3759	if (verbose) {
3760		/* display both BSS and local settings */
3761		for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++) {
3762	again:
3763			if (ac & IEEE80211_WMEPARAM_BSS)
3764				list_wme_aci(s, "     ", ac);
3765			else
3766				list_wme_aci(s, acnames[ac], ac);
3767			if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
3768				ac |= IEEE80211_WMEPARAM_BSS;
3769				goto again;
3770			} else
3771				ac &= ~IEEE80211_WMEPARAM_BSS;
3772		}
3773	} else {
3774		/* display only channel settings */
3775		for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++)
3776			list_wme_aci(s, acnames[ac], ac);
3777	}
3778}
3779
3780static void
3781list_roam(int s)
3782{
3783	const struct ieee80211_roamparam *rp;
3784	int mode;
3785
3786	getroam(s);
3787	for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
3788		rp = &roamparams.params[mode];
3789		if (rp->rssi == 0 && rp->rate == 0)
3790			continue;
3791		if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
3792			if (rp->rssi & 1)
3793				LINE_CHECK("roam:%-7.7s rssi %2u.5dBm  MCS %2u    ",
3794				    modename[mode], rp->rssi/2,
3795				    rp->rate &~ IEEE80211_RATE_MCS);
3796			else
3797				LINE_CHECK("roam:%-7.7s rssi %4udBm  MCS %2u    ",
3798				    modename[mode], rp->rssi/2,
3799				    rp->rate &~ IEEE80211_RATE_MCS);
3800		} else {
3801			if (rp->rssi & 1)
3802				LINE_CHECK("roam:%-7.7s rssi %2u.5dBm rate %2u Mb/s",
3803				    modename[mode], rp->rssi/2, rp->rate/2);
3804			else
3805				LINE_CHECK("roam:%-7.7s rssi %4udBm rate %2u Mb/s",
3806				    modename[mode], rp->rssi/2, rp->rate/2);
3807		}
3808	}
3809}
3810
3811static void
3812list_txparams(int s)
3813{
3814	const struct ieee80211_txparam *tp;
3815	int mode;
3816
3817	gettxparams(s);
3818	for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
3819		tp = &txparams.params[mode];
3820		if (tp->mgmtrate == 0 && tp->mcastrate == 0)
3821			continue;
3822		if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
3823			if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
3824				LINE_CHECK("%-7.7s ucast NONE    mgmt %2u MCS  "
3825				    "mcast %2u MCS  maxretry %u",
3826				    modename[mode],
3827				    tp->mgmtrate &~ IEEE80211_RATE_MCS,
3828				    tp->mcastrate &~ IEEE80211_RATE_MCS,
3829				    tp->maxretry);
3830			else
3831				LINE_CHECK("%-7.7s ucast %2u MCS  mgmt %2u MCS  "
3832				    "mcast %2u MCS  maxretry %u",
3833				    modename[mode],
3834				    tp->ucastrate &~ IEEE80211_RATE_MCS,
3835				    tp->mgmtrate &~ IEEE80211_RATE_MCS,
3836				    tp->mcastrate &~ IEEE80211_RATE_MCS,
3837				    tp->maxretry);
3838		} else {
3839			if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
3840				LINE_CHECK("%-7.7s ucast NONE    mgmt %2u Mb/s "
3841				    "mcast %2u Mb/s maxretry %u",
3842				    modename[mode],
3843				    tp->mgmtrate/2,
3844				    tp->mcastrate/2, tp->maxretry);
3845			else
3846				LINE_CHECK("%-7.7s ucast %2u Mb/s mgmt %2u Mb/s "
3847				    "mcast %2u Mb/s maxretry %u",
3848				    modename[mode],
3849				    tp->ucastrate/2, tp->mgmtrate/2,
3850				    tp->mcastrate/2, tp->maxretry);
3851		}
3852	}
3853}
3854
3855static void
3856printpolicy(int policy)
3857{
3858	switch (policy) {
3859	case IEEE80211_MACCMD_POLICY_OPEN:
3860		printf("policy: open\n");
3861		break;
3862	case IEEE80211_MACCMD_POLICY_ALLOW:
3863		printf("policy: allow\n");
3864		break;
3865	case IEEE80211_MACCMD_POLICY_DENY:
3866		printf("policy: deny\n");
3867		break;
3868	case IEEE80211_MACCMD_POLICY_RADIUS:
3869		printf("policy: radius\n");
3870		break;
3871	default:
3872		printf("policy: unknown (%u)\n", policy);
3873		break;
3874	}
3875}
3876
3877static void
3878list_mac(int s)
3879{
3880	struct ieee80211req ireq;
3881	struct ieee80211req_maclist *acllist;
3882	int i, nacls, policy, len;
3883	uint8_t *data;
3884	char c;
3885
3886	(void) memset(&ireq, 0, sizeof(ireq));
3887	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name)); /* XXX ?? */
3888	ireq.i_type = IEEE80211_IOC_MACCMD;
3889	ireq.i_val = IEEE80211_MACCMD_POLICY;
3890	if (ioctl(s, SIOCG80211, &ireq) < 0) {
3891		if (errno == EINVAL) {
3892			printf("No acl policy loaded\n");
3893			return;
3894		}
3895		err(1, "unable to get mac policy");
3896	}
3897	policy = ireq.i_val;
3898	if (policy == IEEE80211_MACCMD_POLICY_OPEN) {
3899		c = '*';
3900	} else if (policy == IEEE80211_MACCMD_POLICY_ALLOW) {
3901		c = '+';
3902	} else if (policy == IEEE80211_MACCMD_POLICY_DENY) {
3903		c = '-';
3904	} else if (policy == IEEE80211_MACCMD_POLICY_RADIUS) {
3905		c = 'r';		/* NB: should never have entries */
3906	} else {
3907		printf("policy: unknown (%u)\n", policy);
3908		c = '?';
3909	}
3910	if (verbose || c == '?')
3911		printpolicy(policy);
3912
3913	ireq.i_val = IEEE80211_MACCMD_LIST;
3914	ireq.i_len = 0;
3915	if (ioctl(s, SIOCG80211, &ireq) < 0)
3916		err(1, "unable to get mac acl list size");
3917	if (ireq.i_len == 0) {		/* NB: no acls */
3918		if (!(verbose || c == '?'))
3919			printpolicy(policy);
3920		return;
3921	}
3922	len = ireq.i_len;
3923
3924	data = malloc(len);
3925	if (data == NULL)
3926		err(1, "out of memory for acl list");
3927
3928	ireq.i_data = data;
3929	if (ioctl(s, SIOCG80211, &ireq) < 0)
3930		err(1, "unable to get mac acl list");
3931	nacls = len / sizeof(*acllist);
3932	acllist = (struct ieee80211req_maclist *) data;
3933	for (i = 0; i < nacls; i++)
3934		printf("%c%s\n", c, ether_ntoa(
3935			(const struct ether_addr *) acllist[i].ml_macaddr));
3936	free(data);
3937}
3938
3939static void
3940print_regdomain(const struct ieee80211_regdomain *reg, int verb)
3941{
3942	if ((reg->regdomain != 0 &&
3943	    reg->regdomain != reg->country) || verb) {
3944		const struct regdomain *rd =
3945		    lib80211_regdomain_findbysku(getregdata(), reg->regdomain);
3946		if (rd == NULL)
3947			LINE_CHECK("regdomain %d", reg->regdomain);
3948		else
3949			LINE_CHECK("regdomain %s", rd->name);
3950	}
3951	if (reg->country != 0 || verb) {
3952		const struct country *cc =
3953		    lib80211_country_findbycc(getregdata(), reg->country);
3954		if (cc == NULL)
3955			LINE_CHECK("country %d", reg->country);
3956		else
3957			LINE_CHECK("country %s", cc->isoname);
3958	}
3959	if (reg->location == 'I')
3960		LINE_CHECK("indoor");
3961	else if (reg->location == 'O')
3962		LINE_CHECK("outdoor");
3963	else if (verb)
3964		LINE_CHECK("anywhere");
3965	if (reg->ecm)
3966		LINE_CHECK("ecm");
3967	else if (verb)
3968		LINE_CHECK("-ecm");
3969}
3970
3971static void
3972list_regdomain(int s, int channelsalso)
3973{
3974	getregdomain(s);
3975	if (channelsalso) {
3976		getchaninfo(s);
3977		spacer = ':';
3978		print_regdomain(&regdomain, 1);
3979		LINE_BREAK();
3980		print_channels(s, chaninfo, 1/*allchans*/, 1/*verbose*/);
3981	} else
3982		print_regdomain(&regdomain, verbose);
3983}
3984
3985static void
3986list_mesh(int s)
3987{
3988	struct ieee80211req ireq;
3989	struct ieee80211req_mesh_route routes[128];
3990	struct ieee80211req_mesh_route *rt;
3991
3992	(void) memset(&ireq, 0, sizeof(ireq));
3993	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3994	ireq.i_type = IEEE80211_IOC_MESH_RTCMD;
3995	ireq.i_val = IEEE80211_MESH_RTCMD_LIST;
3996	ireq.i_data = &routes;
3997	ireq.i_len = sizeof(routes);
3998	if (ioctl(s, SIOCG80211, &ireq) < 0)
3999	 	err(1, "unable to get the Mesh routing table");
4000
4001	printf("%-17.17s %-17.17s %4s %4s %4s %6s %s\n"
4002		, "DEST"
4003		, "NEXT HOP"
4004		, "HOPS"
4005		, "METRIC"
4006		, "LIFETIME"
4007		, "MSEQ"
4008		, "FLAGS");
4009
4010	for (rt = &routes[0]; rt - &routes[0] < ireq.i_len / sizeof(*rt); rt++){
4011		printf("%s ",
4012		    ether_ntoa((const struct ether_addr *)rt->imr_dest));
4013		printf("%s %4u   %4u   %6u %6u    %c%c\n",
4014			ether_ntoa((const struct ether_addr *)rt->imr_nexthop),
4015			rt->imr_nhops, rt->imr_metric, rt->imr_lifetime,
4016			rt->imr_lastmseq,
4017			(rt->imr_flags & IEEE80211_MESHRT_FLAGS_VALID) ?
4018			    'V' : '!',
4019			(rt->imr_flags & IEEE80211_MESHRT_FLAGS_PROXY) ?
4020			    'P' : ' ');
4021	}
4022}
4023
4024static
4025DECL_CMD_FUNC(set80211list, arg, d)
4026{
4027#define	iseq(a,b)	(strncasecmp(a,b,sizeof(b)-1) == 0)
4028
4029	LINE_INIT('\t');
4030
4031	if (iseq(arg, "sta"))
4032		list_stations(s);
4033	else if (iseq(arg, "scan") || iseq(arg, "ap"))
4034		list_scan(s);
4035	else if (iseq(arg, "chan") || iseq(arg, "freq"))
4036		list_channels(s, 1);
4037	else if (iseq(arg, "active"))
4038		list_channels(s, 0);
4039	else if (iseq(arg, "keys"))
4040		list_keys(s);
4041	else if (iseq(arg, "caps"))
4042		list_capabilities(s);
4043	else if (iseq(arg, "wme") || iseq(arg, "wmm"))
4044		list_wme(s);
4045	else if (iseq(arg, "mac"))
4046		list_mac(s);
4047	else if (iseq(arg, "txpow"))
4048		list_txpow(s);
4049	else if (iseq(arg, "roam"))
4050		list_roam(s);
4051	else if (iseq(arg, "txparam") || iseq(arg, "txparm"))
4052		list_txparams(s);
4053	else if (iseq(arg, "regdomain"))
4054		list_regdomain(s, 1);
4055	else if (iseq(arg, "countries"))
4056		list_countries();
4057	else if (iseq(arg, "mesh"))
4058		list_mesh(s);
4059	else
4060		errx(1, "Don't know how to list %s for %s", arg, name);
4061	LINE_BREAK();
4062#undef iseq
4063}
4064
4065static enum ieee80211_opmode
4066get80211opmode(int s)
4067{
4068	struct ifmediareq ifmr;
4069
4070	(void) memset(&ifmr, 0, sizeof(ifmr));
4071	(void) strncpy(ifmr.ifm_name, name, sizeof(ifmr.ifm_name));
4072
4073	if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0) {
4074		if (ifmr.ifm_current & IFM_IEEE80211_ADHOC) {
4075			if (ifmr.ifm_current & IFM_FLAG0)
4076				return IEEE80211_M_AHDEMO;
4077			else
4078				return IEEE80211_M_IBSS;
4079		}
4080		if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
4081			return IEEE80211_M_HOSTAP;
4082		if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
4083			return IEEE80211_M_MONITOR;
4084		if (ifmr.ifm_current & IFM_IEEE80211_MBSS)
4085			return IEEE80211_M_MBSS;
4086	}
4087	return IEEE80211_M_STA;
4088}
4089
4090#if 0
4091static void
4092printcipher(int s, struct ieee80211req *ireq, int keylenop)
4093{
4094	switch (ireq->i_val) {
4095	case IEEE80211_CIPHER_WEP:
4096		ireq->i_type = keylenop;
4097		if (ioctl(s, SIOCG80211, ireq) != -1)
4098			printf("WEP-%s",
4099			    ireq->i_len <= 5 ? "40" :
4100			    ireq->i_len <= 13 ? "104" : "128");
4101		else
4102			printf("WEP");
4103		break;
4104	case IEEE80211_CIPHER_TKIP:
4105		printf("TKIP");
4106		break;
4107	case IEEE80211_CIPHER_AES_OCB:
4108		printf("AES-OCB");
4109		break;
4110	case IEEE80211_CIPHER_AES_CCM:
4111		printf("AES-CCM");
4112		break;
4113	case IEEE80211_CIPHER_CKIP:
4114		printf("CKIP");
4115		break;
4116	case IEEE80211_CIPHER_NONE:
4117		printf("NONE");
4118		break;
4119	default:
4120		printf("UNKNOWN (0x%x)", ireq->i_val);
4121		break;
4122	}
4123}
4124#endif
4125
4126static void
4127printkey(const struct ieee80211req_key *ik)
4128{
4129	static const uint8_t zerodata[IEEE80211_KEYBUF_SIZE];
4130	int keylen = ik->ik_keylen;
4131	int printcontents;
4132
4133	printcontents = printkeys &&
4134		(memcmp(ik->ik_keydata, zerodata, keylen) != 0 || verbose);
4135	if (printcontents)
4136		LINE_BREAK();
4137	switch (ik->ik_type) {
4138	case IEEE80211_CIPHER_WEP:
4139		/* compatibility */
4140		LINE_CHECK("wepkey %u:%s", ik->ik_keyix+1,
4141		    keylen <= 5 ? "40-bit" :
4142		    keylen <= 13 ? "104-bit" : "128-bit");
4143		break;
4144	case IEEE80211_CIPHER_TKIP:
4145		if (keylen > 128/8)
4146			keylen -= 128/8;	/* ignore MIC for now */
4147		LINE_CHECK("TKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4148		break;
4149	case IEEE80211_CIPHER_AES_OCB:
4150		LINE_CHECK("AES-OCB %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4151		break;
4152	case IEEE80211_CIPHER_AES_CCM:
4153		LINE_CHECK("AES-CCM %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4154		break;
4155	case IEEE80211_CIPHER_CKIP:
4156		LINE_CHECK("CKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4157		break;
4158	case IEEE80211_CIPHER_NONE:
4159		LINE_CHECK("NULL %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4160		break;
4161	default:
4162		LINE_CHECK("UNKNOWN (0x%x) %u:%u-bit",
4163			ik->ik_type, ik->ik_keyix+1, 8*keylen);
4164		break;
4165	}
4166	if (printcontents) {
4167		int i;
4168
4169		printf(" <");
4170		for (i = 0; i < keylen; i++)
4171			printf("%02x", ik->ik_keydata[i]);
4172		printf(">");
4173		if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4174		    (ik->ik_keyrsc != 0 || verbose))
4175			printf(" rsc %ju", (uintmax_t)ik->ik_keyrsc);
4176		if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4177		    (ik->ik_keytsc != 0 || verbose))
4178			printf(" tsc %ju", (uintmax_t)ik->ik_keytsc);
4179		if (ik->ik_flags != 0 && verbose) {
4180			const char *sep = " ";
4181
4182			if (ik->ik_flags & IEEE80211_KEY_XMIT)
4183				printf("%stx", sep), sep = "+";
4184			if (ik->ik_flags & IEEE80211_KEY_RECV)
4185				printf("%srx", sep), sep = "+";
4186			if (ik->ik_flags & IEEE80211_KEY_DEFAULT)
4187				printf("%sdef", sep), sep = "+";
4188		}
4189		LINE_BREAK();
4190	}
4191}
4192
4193static void
4194printrate(const char *tag, int v, int defrate, int defmcs)
4195{
4196	if ((v & IEEE80211_RATE_MCS) == 0) {
4197		if (v != defrate) {
4198			if (v & 1)
4199				LINE_CHECK("%s %d.5", tag, v/2);
4200			else
4201				LINE_CHECK("%s %d", tag, v/2);
4202		}
4203	} else {
4204		if (v != defmcs)
4205			LINE_CHECK("%s %d", tag, v &~ 0x80);
4206	}
4207}
4208
4209static int
4210getid(int s, int ix, void *data, size_t len, int *plen, int mesh)
4211{
4212	struct ieee80211req ireq;
4213
4214	(void) memset(&ireq, 0, sizeof(ireq));
4215	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4216	ireq.i_type = (!mesh) ? IEEE80211_IOC_SSID : IEEE80211_IOC_MESH_ID;
4217	ireq.i_val = ix;
4218	ireq.i_data = data;
4219	ireq.i_len = len;
4220	if (ioctl(s, SIOCG80211, &ireq) < 0)
4221		return -1;
4222	*plen = ireq.i_len;
4223	return 0;
4224}
4225
4226static void
4227ieee80211_status(int s)
4228{
4229	static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
4230	enum ieee80211_opmode opmode = get80211opmode(s);
4231	int i, num, wpa, wme, bgscan, bgscaninterval, val, len, wepmode;
4232	uint8_t data[32];
4233	const struct ieee80211_channel *c;
4234	const struct ieee80211_roamparam *rp;
4235	const struct ieee80211_txparam *tp;
4236
4237	if (getid(s, -1, data, sizeof(data), &len, 0) < 0) {
4238		/* If we can't get the SSID, this isn't an 802.11 device. */
4239		return;
4240	}
4241
4242	/*
4243	 * Invalidate cached state so printing status for multiple
4244	 * if's doesn't reuse the first interfaces' cached state.
4245	 */
4246	gotcurchan = 0;
4247	gotroam = 0;
4248	gottxparams = 0;
4249	gothtconf = 0;
4250	gotregdomain = 0;
4251
4252	printf("\t");
4253	if (opmode == IEEE80211_M_MBSS) {
4254		printf("meshid ");
4255		getid(s, 0, data, sizeof(data), &len, 1);
4256		print_string(data, len);
4257	} else {
4258		if (get80211val(s, IEEE80211_IOC_NUMSSIDS, &num) < 0)
4259			num = 0;
4260		printf("ssid ");
4261		if (num > 1) {
4262			for (i = 0; i < num; i++) {
4263				if (getid(s, i, data, sizeof(data), &len, 0) >= 0 && len > 0) {
4264					printf(" %d:", i + 1);
4265					print_string(data, len);
4266				}
4267			}
4268		} else
4269			print_string(data, len);
4270	}
4271	c = getcurchan(s);
4272	if (c->ic_freq != IEEE80211_CHAN_ANY) {
4273		char buf[14];
4274		printf(" channel %d (%u MHz%s)", c->ic_ieee, c->ic_freq,
4275			get_chaninfo(c, 1, buf, sizeof(buf)));
4276	} else if (verbose)
4277		printf(" channel UNDEF");
4278
4279	if (get80211(s, IEEE80211_IOC_BSSID, data, IEEE80211_ADDR_LEN) >= 0 &&
4280	    (memcmp(data, zerobssid, sizeof(zerobssid)) != 0 || verbose))
4281		printf(" bssid %s", ether_ntoa((struct ether_addr *)data));
4282
4283	if (get80211len(s, IEEE80211_IOC_STATIONNAME, data, sizeof(data), &len) != -1) {
4284		printf("\n\tstationname ");
4285		print_string(data, len);
4286	}
4287
4288	spacer = ' ';		/* force first break */
4289	LINE_BREAK();
4290
4291	list_regdomain(s, 0);
4292
4293	wpa = 0;
4294	if (get80211val(s, IEEE80211_IOC_AUTHMODE, &val) != -1) {
4295		switch (val) {
4296		case IEEE80211_AUTH_NONE:
4297			LINE_CHECK("authmode NONE");
4298			break;
4299		case IEEE80211_AUTH_OPEN:
4300			LINE_CHECK("authmode OPEN");
4301			break;
4302		case IEEE80211_AUTH_SHARED:
4303			LINE_CHECK("authmode SHARED");
4304			break;
4305		case IEEE80211_AUTH_8021X:
4306			LINE_CHECK("authmode 802.1x");
4307			break;
4308		case IEEE80211_AUTH_WPA:
4309			if (get80211val(s, IEEE80211_IOC_WPA, &wpa) < 0)
4310				wpa = 1;	/* default to WPA1 */
4311			switch (wpa) {
4312			case 2:
4313				LINE_CHECK("authmode WPA2/802.11i");
4314				break;
4315			case 3:
4316				LINE_CHECK("authmode WPA1+WPA2/802.11i");
4317				break;
4318			default:
4319				LINE_CHECK("authmode WPA");
4320				break;
4321			}
4322			break;
4323		case IEEE80211_AUTH_AUTO:
4324			LINE_CHECK("authmode AUTO");
4325			break;
4326		default:
4327			LINE_CHECK("authmode UNKNOWN (0x%x)", val);
4328			break;
4329		}
4330	}
4331
4332	if (wpa || verbose) {
4333		if (get80211val(s, IEEE80211_IOC_WPS, &val) != -1) {
4334			if (val)
4335				LINE_CHECK("wps");
4336			else if (verbose)
4337				LINE_CHECK("-wps");
4338		}
4339		if (get80211val(s, IEEE80211_IOC_TSN, &val) != -1) {
4340			if (val)
4341				LINE_CHECK("tsn");
4342			else if (verbose)
4343				LINE_CHECK("-tsn");
4344		}
4345		if (ioctl(s, IEEE80211_IOC_COUNTERMEASURES, &val) != -1) {
4346			if (val)
4347				LINE_CHECK("countermeasures");
4348			else if (verbose)
4349				LINE_CHECK("-countermeasures");
4350		}
4351#if 0
4352		/* XXX not interesting with WPA done in user space */
4353		ireq.i_type = IEEE80211_IOC_KEYMGTALGS;
4354		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4355		}
4356
4357		ireq.i_type = IEEE80211_IOC_MCASTCIPHER;
4358		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4359			LINE_CHECK("mcastcipher ");
4360			printcipher(s, &ireq, IEEE80211_IOC_MCASTKEYLEN);
4361			spacer = ' ';
4362		}
4363
4364		ireq.i_type = IEEE80211_IOC_UCASTCIPHER;
4365		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4366			LINE_CHECK("ucastcipher ");
4367			printcipher(s, &ireq, IEEE80211_IOC_UCASTKEYLEN);
4368		}
4369
4370		if (wpa & 2) {
4371			ireq.i_type = IEEE80211_IOC_RSNCAPS;
4372			if (ioctl(s, SIOCG80211, &ireq) != -1) {
4373				LINE_CHECK("RSN caps 0x%x", ireq.i_val);
4374				spacer = ' ';
4375			}
4376		}
4377
4378		ireq.i_type = IEEE80211_IOC_UCASTCIPHERS;
4379		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4380		}
4381#endif
4382	}
4383
4384	if (get80211val(s, IEEE80211_IOC_WEP, &wepmode) != -1 &&
4385	    wepmode != IEEE80211_WEP_NOSUP) {
4386		int firstkey;
4387
4388		switch (wepmode) {
4389		case IEEE80211_WEP_OFF:
4390			LINE_CHECK("privacy OFF");
4391			break;
4392		case IEEE80211_WEP_ON:
4393			LINE_CHECK("privacy ON");
4394			break;
4395		case IEEE80211_WEP_MIXED:
4396			LINE_CHECK("privacy MIXED");
4397			break;
4398		default:
4399			LINE_CHECK("privacy UNKNOWN (0x%x)", wepmode);
4400			break;
4401		}
4402
4403		/*
4404		 * If we get here then we've got WEP support so we need
4405		 * to print WEP status.
4406		 */
4407
4408		if (get80211val(s, IEEE80211_IOC_WEPTXKEY, &val) < 0) {
4409			warn("WEP support, but no tx key!");
4410			goto end;
4411		}
4412		if (val != -1)
4413			LINE_CHECK("deftxkey %d", val+1);
4414		else if (wepmode != IEEE80211_WEP_OFF || verbose)
4415			LINE_CHECK("deftxkey UNDEF");
4416
4417		if (get80211val(s, IEEE80211_IOC_NUMWEPKEYS, &num) < 0) {
4418			warn("WEP support, but no NUMWEPKEYS support!");
4419			goto end;
4420		}
4421
4422		firstkey = 1;
4423		for (i = 0; i < num; i++) {
4424			struct ieee80211req_key ik;
4425
4426			memset(&ik, 0, sizeof(ik));
4427			ik.ik_keyix = i;
4428			if (get80211(s, IEEE80211_IOC_WPAKEY, &ik, sizeof(ik)) < 0) {
4429				warn("WEP support, but can get keys!");
4430				goto end;
4431			}
4432			if (ik.ik_keylen != 0) {
4433				if (verbose)
4434					LINE_BREAK();
4435				printkey(&ik);
4436				firstkey = 0;
4437			}
4438		}
4439end:
4440		;
4441	}
4442
4443	if (get80211val(s, IEEE80211_IOC_POWERSAVE, &val) != -1 &&
4444	    val != IEEE80211_POWERSAVE_NOSUP ) {
4445		if (val != IEEE80211_POWERSAVE_OFF || verbose) {
4446			switch (val) {
4447			case IEEE80211_POWERSAVE_OFF:
4448				LINE_CHECK("powersavemode OFF");
4449				break;
4450			case IEEE80211_POWERSAVE_CAM:
4451				LINE_CHECK("powersavemode CAM");
4452				break;
4453			case IEEE80211_POWERSAVE_PSP:
4454				LINE_CHECK("powersavemode PSP");
4455				break;
4456			case IEEE80211_POWERSAVE_PSP_CAM:
4457				LINE_CHECK("powersavemode PSP-CAM");
4458				break;
4459			}
4460			if (get80211val(s, IEEE80211_IOC_POWERSAVESLEEP, &val) != -1)
4461				LINE_CHECK("powersavesleep %d", val);
4462		}
4463	}
4464
4465	if (get80211val(s, IEEE80211_IOC_TXPOWER, &val) != -1) {
4466		if (val & 1)
4467			LINE_CHECK("txpower %d.5", val/2);
4468		else
4469			LINE_CHECK("txpower %d", val/2);
4470	}
4471	if (verbose) {
4472		if (get80211val(s, IEEE80211_IOC_TXPOWMAX, &val) != -1)
4473			LINE_CHECK("txpowmax %.1f", val/2.);
4474	}
4475
4476	if (get80211val(s, IEEE80211_IOC_DOTD, &val) != -1) {
4477		if (val)
4478			LINE_CHECK("dotd");
4479		else if (verbose)
4480			LINE_CHECK("-dotd");
4481	}
4482
4483	if (get80211val(s, IEEE80211_IOC_RTSTHRESHOLD, &val) != -1) {
4484		if (val != IEEE80211_RTS_MAX || verbose)
4485			LINE_CHECK("rtsthreshold %d", val);
4486	}
4487
4488	if (get80211val(s, IEEE80211_IOC_FRAGTHRESHOLD, &val) != -1) {
4489		if (val != IEEE80211_FRAG_MAX || verbose)
4490			LINE_CHECK("fragthreshold %d", val);
4491	}
4492	if (opmode == IEEE80211_M_STA || verbose) {
4493		if (get80211val(s, IEEE80211_IOC_BMISSTHRESHOLD, &val) != -1) {
4494			if (val != IEEE80211_HWBMISS_MAX || verbose)
4495				LINE_CHECK("bmiss %d", val);
4496		}
4497	}
4498
4499	if (!verbose) {
4500		gettxparams(s);
4501		tp = &txparams.params[chan2mode(c)];
4502		printrate("ucastrate", tp->ucastrate,
4503		    IEEE80211_FIXED_RATE_NONE, IEEE80211_FIXED_RATE_NONE);
4504		printrate("mcastrate", tp->mcastrate, 2*1,
4505		    IEEE80211_RATE_MCS|0);
4506		printrate("mgmtrate", tp->mgmtrate, 2*1,
4507		    IEEE80211_RATE_MCS|0);
4508		if (tp->maxretry != 6)		/* XXX */
4509			LINE_CHECK("maxretry %d", tp->maxretry);
4510	} else {
4511		LINE_BREAK();
4512		list_txparams(s);
4513	}
4514
4515	bgscaninterval = -1;
4516	(void) get80211val(s, IEEE80211_IOC_BGSCAN_INTERVAL, &bgscaninterval);
4517
4518	if (get80211val(s, IEEE80211_IOC_SCANVALID, &val) != -1) {
4519		if (val != bgscaninterval || verbose)
4520			LINE_CHECK("scanvalid %u", val);
4521	}
4522
4523	bgscan = 0;
4524	if (get80211val(s, IEEE80211_IOC_BGSCAN, &bgscan) != -1) {
4525		if (bgscan)
4526			LINE_CHECK("bgscan");
4527		else if (verbose)
4528			LINE_CHECK("-bgscan");
4529	}
4530	if (bgscan || verbose) {
4531		if (bgscaninterval != -1)
4532			LINE_CHECK("bgscanintvl %u", bgscaninterval);
4533		if (get80211val(s, IEEE80211_IOC_BGSCAN_IDLE, &val) != -1)
4534			LINE_CHECK("bgscanidle %u", val);
4535		if (!verbose) {
4536			getroam(s);
4537			rp = &roamparams.params[chan2mode(c)];
4538			if (rp->rssi & 1)
4539				LINE_CHECK("roam:rssi %u.5", rp->rssi/2);
4540			else
4541				LINE_CHECK("roam:rssi %u", rp->rssi/2);
4542			LINE_CHECK("roam:rate %u", rp->rate/2);
4543		} else {
4544			LINE_BREAK();
4545			list_roam(s);
4546			LINE_BREAK();
4547		}
4548	}
4549
4550	if (IEEE80211_IS_CHAN_ANYG(c) || verbose) {
4551		if (get80211val(s, IEEE80211_IOC_PUREG, &val) != -1) {
4552			if (val)
4553				LINE_CHECK("pureg");
4554			else if (verbose)
4555				LINE_CHECK("-pureg");
4556		}
4557		if (get80211val(s, IEEE80211_IOC_PROTMODE, &val) != -1) {
4558			switch (val) {
4559			case IEEE80211_PROTMODE_OFF:
4560				LINE_CHECK("protmode OFF");
4561				break;
4562			case IEEE80211_PROTMODE_CTS:
4563				LINE_CHECK("protmode CTS");
4564				break;
4565			case IEEE80211_PROTMODE_RTSCTS:
4566				LINE_CHECK("protmode RTSCTS");
4567				break;
4568			default:
4569				LINE_CHECK("protmode UNKNOWN (0x%x)", val);
4570				break;
4571			}
4572		}
4573	}
4574
4575	if (IEEE80211_IS_CHAN_HT(c) || verbose) {
4576		gethtconf(s);
4577		switch (htconf & 3) {
4578		case 0:
4579		case 2:
4580			LINE_CHECK("-ht");
4581			break;
4582		case 1:
4583			LINE_CHECK("ht20");
4584			break;
4585		case 3:
4586			if (verbose)
4587				LINE_CHECK("ht");
4588			break;
4589		}
4590		if (get80211val(s, IEEE80211_IOC_HTCOMPAT, &val) != -1) {
4591			if (!val)
4592				LINE_CHECK("-htcompat");
4593			else if (verbose)
4594				LINE_CHECK("htcompat");
4595		}
4596		if (get80211val(s, IEEE80211_IOC_AMPDU, &val) != -1) {
4597			switch (val) {
4598			case 0:
4599				LINE_CHECK("-ampdu");
4600				break;
4601			case 1:
4602				LINE_CHECK("ampdutx -ampdurx");
4603				break;
4604			case 2:
4605				LINE_CHECK("-ampdutx ampdurx");
4606				break;
4607			case 3:
4608				if (verbose)
4609					LINE_CHECK("ampdu");
4610				break;
4611			}
4612		}
4613		if (get80211val(s, IEEE80211_IOC_AMPDU_LIMIT, &val) != -1) {
4614			switch (val) {
4615			case IEEE80211_HTCAP_MAXRXAMPDU_8K:
4616				LINE_CHECK("ampdulimit 8k");
4617				break;
4618			case IEEE80211_HTCAP_MAXRXAMPDU_16K:
4619				LINE_CHECK("ampdulimit 16k");
4620				break;
4621			case IEEE80211_HTCAP_MAXRXAMPDU_32K:
4622				LINE_CHECK("ampdulimit 32k");
4623				break;
4624			case IEEE80211_HTCAP_MAXRXAMPDU_64K:
4625				LINE_CHECK("ampdulimit 64k");
4626				break;
4627			}
4628		}
4629		if (get80211val(s, IEEE80211_IOC_AMPDU_DENSITY, &val) != -1) {
4630			switch (val) {
4631			case IEEE80211_HTCAP_MPDUDENSITY_NA:
4632				if (verbose)
4633					LINE_CHECK("ampdudensity NA");
4634				break;
4635			case IEEE80211_HTCAP_MPDUDENSITY_025:
4636				LINE_CHECK("ampdudensity .25");
4637				break;
4638			case IEEE80211_HTCAP_MPDUDENSITY_05:
4639				LINE_CHECK("ampdudensity .5");
4640				break;
4641			case IEEE80211_HTCAP_MPDUDENSITY_1:
4642				LINE_CHECK("ampdudensity 1");
4643				break;
4644			case IEEE80211_HTCAP_MPDUDENSITY_2:
4645				LINE_CHECK("ampdudensity 2");
4646				break;
4647			case IEEE80211_HTCAP_MPDUDENSITY_4:
4648				LINE_CHECK("ampdudensity 4");
4649				break;
4650			case IEEE80211_HTCAP_MPDUDENSITY_8:
4651				LINE_CHECK("ampdudensity 8");
4652				break;
4653			case IEEE80211_HTCAP_MPDUDENSITY_16:
4654				LINE_CHECK("ampdudensity 16");
4655				break;
4656			}
4657		}
4658		if (get80211val(s, IEEE80211_IOC_AMSDU, &val) != -1) {
4659			switch (val) {
4660			case 0:
4661				LINE_CHECK("-amsdu");
4662				break;
4663			case 1:
4664				LINE_CHECK("amsdutx -amsdurx");
4665				break;
4666			case 2:
4667				LINE_CHECK("-amsdutx amsdurx");
4668				break;
4669			case 3:
4670				if (verbose)
4671					LINE_CHECK("amsdu");
4672				break;
4673			}
4674		}
4675		/* XXX amsdu limit */
4676		if (get80211val(s, IEEE80211_IOC_SHORTGI, &val) != -1) {
4677			if (val)
4678				LINE_CHECK("shortgi");
4679			else if (verbose)
4680				LINE_CHECK("-shortgi");
4681		}
4682		if (get80211val(s, IEEE80211_IOC_HTPROTMODE, &val) != -1) {
4683			if (val == IEEE80211_PROTMODE_OFF)
4684				LINE_CHECK("htprotmode OFF");
4685			else if (val != IEEE80211_PROTMODE_RTSCTS)
4686				LINE_CHECK("htprotmode UNKNOWN (0x%x)", val);
4687			else if (verbose)
4688				LINE_CHECK("htprotmode RTSCTS");
4689		}
4690		if (get80211val(s, IEEE80211_IOC_PUREN, &val) != -1) {
4691			if (val)
4692				LINE_CHECK("puren");
4693			else if (verbose)
4694				LINE_CHECK("-puren");
4695		}
4696		if (get80211val(s, IEEE80211_IOC_SMPS, &val) != -1) {
4697			if (val == IEEE80211_HTCAP_SMPS_DYNAMIC)
4698				LINE_CHECK("smpsdyn");
4699			else if (val == IEEE80211_HTCAP_SMPS_ENA)
4700				LINE_CHECK("smps");
4701			else if (verbose)
4702				LINE_CHECK("-smps");
4703		}
4704		if (get80211val(s, IEEE80211_IOC_RIFS, &val) != -1) {
4705			if (val)
4706				LINE_CHECK("rifs");
4707			else if (verbose)
4708				LINE_CHECK("-rifs");
4709		}
4710	}
4711
4712	if (get80211val(s, IEEE80211_IOC_WME, &wme) != -1) {
4713		if (wme)
4714			LINE_CHECK("wme");
4715		else if (verbose)
4716			LINE_CHECK("-wme");
4717	} else
4718		wme = 0;
4719
4720	if (get80211val(s, IEEE80211_IOC_BURST, &val) != -1) {
4721		if (val)
4722			LINE_CHECK("burst");
4723		else if (verbose)
4724			LINE_CHECK("-burst");
4725	}
4726
4727	if (get80211val(s, IEEE80211_IOC_FF, &val) != -1) {
4728		if (val)
4729			LINE_CHECK("ff");
4730		else if (verbose)
4731			LINE_CHECK("-ff");
4732	}
4733	if (get80211val(s, IEEE80211_IOC_TURBOP, &val) != -1) {
4734		if (val)
4735			LINE_CHECK("dturbo");
4736		else if (verbose)
4737			LINE_CHECK("-dturbo");
4738	}
4739	if (get80211val(s, IEEE80211_IOC_DWDS, &val) != -1) {
4740		if (val)
4741			LINE_CHECK("dwds");
4742		else if (verbose)
4743			LINE_CHECK("-dwds");
4744	}
4745
4746	if (opmode == IEEE80211_M_HOSTAP) {
4747		if (get80211val(s, IEEE80211_IOC_HIDESSID, &val) != -1) {
4748			if (val)
4749				LINE_CHECK("hidessid");
4750			else if (verbose)
4751				LINE_CHECK("-hidessid");
4752		}
4753		if (get80211val(s, IEEE80211_IOC_APBRIDGE, &val) != -1) {
4754			if (!val)
4755				LINE_CHECK("-apbridge");
4756			else if (verbose)
4757				LINE_CHECK("apbridge");
4758		}
4759		if (get80211val(s, IEEE80211_IOC_DTIM_PERIOD, &val) != -1)
4760			LINE_CHECK("dtimperiod %u", val);
4761
4762		if (get80211val(s, IEEE80211_IOC_DOTH, &val) != -1) {
4763			if (!val)
4764				LINE_CHECK("-doth");
4765			else if (verbose)
4766				LINE_CHECK("doth");
4767		}
4768		if (get80211val(s, IEEE80211_IOC_DFS, &val) != -1) {
4769			if (!val)
4770				LINE_CHECK("-dfs");
4771			else if (verbose)
4772				LINE_CHECK("dfs");
4773		}
4774		if (get80211val(s, IEEE80211_IOC_INACTIVITY, &val) != -1) {
4775			if (!val)
4776				LINE_CHECK("-inact");
4777			else if (verbose)
4778				LINE_CHECK("inact");
4779		}
4780	} else {
4781		if (get80211val(s, IEEE80211_IOC_ROAMING, &val) != -1) {
4782			if (val != IEEE80211_ROAMING_AUTO || verbose) {
4783				switch (val) {
4784				case IEEE80211_ROAMING_DEVICE:
4785					LINE_CHECK("roaming DEVICE");
4786					break;
4787				case IEEE80211_ROAMING_AUTO:
4788					LINE_CHECK("roaming AUTO");
4789					break;
4790				case IEEE80211_ROAMING_MANUAL:
4791					LINE_CHECK("roaming MANUAL");
4792					break;
4793				default:
4794					LINE_CHECK("roaming UNKNOWN (0x%x)",
4795						val);
4796					break;
4797				}
4798			}
4799		}
4800	}
4801
4802	if (opmode == IEEE80211_M_AHDEMO) {
4803		if (get80211val(s, IEEE80211_IOC_TDMA_SLOT, &val) != -1)
4804			LINE_CHECK("tdmaslot %u", val);
4805		if (get80211val(s, IEEE80211_IOC_TDMA_SLOTCNT, &val) != -1)
4806			LINE_CHECK("tdmaslotcnt %u", val);
4807		if (get80211val(s, IEEE80211_IOC_TDMA_SLOTLEN, &val) != -1)
4808			LINE_CHECK("tdmaslotlen %u", val);
4809		if (get80211val(s, IEEE80211_IOC_TDMA_BINTERVAL, &val) != -1)
4810			LINE_CHECK("tdmabintval %u", val);
4811	} else if (get80211val(s, IEEE80211_IOC_BEACON_INTERVAL, &val) != -1) {
4812		/* XXX default define not visible */
4813		if (val != 100 || verbose)
4814			LINE_CHECK("bintval %u", val);
4815	}
4816
4817	if (wme && verbose) {
4818		LINE_BREAK();
4819		list_wme(s);
4820	}
4821
4822	if (opmode == IEEE80211_M_MBSS) {
4823		if (get80211val(s, IEEE80211_IOC_MESH_TTL, &val) != -1) {
4824			LINE_CHECK("meshttl %u", val);
4825		}
4826		if (get80211val(s, IEEE80211_IOC_MESH_AP, &val) != -1) {
4827			if (val)
4828				LINE_CHECK("meshpeering");
4829			else
4830				LINE_CHECK("-meshpeering");
4831		}
4832		if (get80211val(s, IEEE80211_IOC_MESH_FWRD, &val) != -1) {
4833			if (val)
4834				LINE_CHECK("meshforward");
4835			else
4836				LINE_CHECK("-meshforward");
4837		}
4838		if (get80211len(s, IEEE80211_IOC_MESH_PR_METRIC, data, 12,
4839		    &len) != -1) {
4840			data[len] = '\0';
4841			LINE_CHECK("meshmetric %s", data);
4842		}
4843		if (get80211len(s, IEEE80211_IOC_MESH_PR_PATH, data, 12,
4844		    &len) != -1) {
4845			data[len] = '\0';
4846			LINE_CHECK("meshpath %s", data);
4847		}
4848		if (get80211val(s, IEEE80211_IOC_HWMP_ROOTMODE, &val) != -1) {
4849			switch (val) {
4850			case IEEE80211_HWMP_ROOTMODE_DISABLED:
4851				LINE_CHECK("hwmprootmode DISABLED");
4852				break;
4853			case IEEE80211_HWMP_ROOTMODE_NORMAL:
4854				LINE_CHECK("hwmprootmode NORMAL");
4855				break;
4856			case IEEE80211_HWMP_ROOTMODE_PROACTIVE:
4857				LINE_CHECK("hwmprootmode PROACTIVE");
4858				break;
4859			case IEEE80211_HWMP_ROOTMODE_RANN:
4860				LINE_CHECK("hwmprootmode RANN");
4861				break;
4862			default:
4863				LINE_CHECK("hwmprootmode UNKNOWN(%d)", val);
4864				break;
4865			}
4866		}
4867		if (get80211val(s, IEEE80211_IOC_HWMP_MAXHOPS, &val) != -1) {
4868			LINE_CHECK("hwmpmaxhops %u", val);
4869		}
4870	}
4871
4872	LINE_BREAK();
4873}
4874
4875static int
4876get80211(int s, int type, void *data, int len)
4877{
4878	struct ieee80211req ireq;
4879
4880	(void) memset(&ireq, 0, sizeof(ireq));
4881	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4882	ireq.i_type = type;
4883	ireq.i_data = data;
4884	ireq.i_len = len;
4885	return ioctl(s, SIOCG80211, &ireq);
4886}
4887
4888static int
4889get80211len(int s, int type, void *data, int len, int *plen)
4890{
4891	struct ieee80211req ireq;
4892
4893	(void) memset(&ireq, 0, sizeof(ireq));
4894	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4895	ireq.i_type = type;
4896	ireq.i_len = len;
4897	assert(ireq.i_len == len);	/* NB: check for 16-bit truncation */
4898	ireq.i_data = data;
4899	if (ioctl(s, SIOCG80211, &ireq) < 0)
4900		return -1;
4901	*plen = ireq.i_len;
4902	return 0;
4903}
4904
4905static int
4906get80211val(int s, int type, int *val)
4907{
4908	struct ieee80211req ireq;
4909
4910	(void) memset(&ireq, 0, sizeof(ireq));
4911	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4912	ireq.i_type = type;
4913	if (ioctl(s, SIOCG80211, &ireq) < 0)
4914		return -1;
4915	*val = ireq.i_val;
4916	return 0;
4917}
4918
4919static void
4920set80211(int s, int type, int val, int len, void *data)
4921{
4922	struct ieee80211req	ireq;
4923
4924	(void) memset(&ireq, 0, sizeof(ireq));
4925	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4926	ireq.i_type = type;
4927	ireq.i_val = val;
4928	ireq.i_len = len;
4929	assert(ireq.i_len == len);	/* NB: check for 16-bit truncation */
4930	ireq.i_data = data;
4931	if (ioctl(s, SIOCS80211, &ireq) < 0)
4932		err(1, "SIOCS80211");
4933}
4934
4935static const char *
4936get_string(const char *val, const char *sep, u_int8_t *buf, int *lenp)
4937{
4938	int len;
4939	int hexstr;
4940	u_int8_t *p;
4941
4942	len = *lenp;
4943	p = buf;
4944	hexstr = (val[0] == '0' && tolower((u_char)val[1]) == 'x');
4945	if (hexstr)
4946		val += 2;
4947	for (;;) {
4948		if (*val == '\0')
4949			break;
4950		if (sep != NULL && strchr(sep, *val) != NULL) {
4951			val++;
4952			break;
4953		}
4954		if (hexstr) {
4955			if (!isxdigit((u_char)val[0])) {
4956				warnx("bad hexadecimal digits");
4957				return NULL;
4958			}
4959			if (!isxdigit((u_char)val[1])) {
4960				warnx("odd count hexadecimal digits");
4961				return NULL;
4962			}
4963		}
4964		if (p >= buf + len) {
4965			if (hexstr)
4966				warnx("hexadecimal digits too long");
4967			else
4968				warnx("string too long");
4969			return NULL;
4970		}
4971		if (hexstr) {
4972#define	tohex(x)	(isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
4973			*p++ = (tohex((u_char)val[0]) << 4) |
4974			    tohex((u_char)val[1]);
4975#undef tohex
4976			val += 2;
4977		} else
4978			*p++ = *val++;
4979	}
4980	len = p - buf;
4981	/* The string "-" is treated as the empty string. */
4982	if (!hexstr && len == 1 && buf[0] == '-') {
4983		len = 0;
4984		memset(buf, 0, *lenp);
4985	} else if (len < *lenp)
4986		memset(p, 0, *lenp - len);
4987	*lenp = len;
4988	return val;
4989}
4990
4991static void
4992print_string(const u_int8_t *buf, int len)
4993{
4994	int i;
4995	int hasspc;
4996
4997	i = 0;
4998	hasspc = 0;
4999	for (; i < len; i++) {
5000		if (!isprint(buf[i]) && buf[i] != '\0')
5001			break;
5002		if (isspace(buf[i]))
5003			hasspc++;
5004	}
5005	if (i == len) {
5006		if (hasspc || len == 0 || buf[0] == '\0')
5007			printf("\"%.*s\"", len, buf);
5008		else
5009			printf("%.*s", len, buf);
5010	} else {
5011		printf("0x");
5012		for (i = 0; i < len; i++)
5013			printf("%02x", buf[i]);
5014	}
5015}
5016
5017/*
5018 * Virtual AP cloning support.
5019 */
5020static struct ieee80211_clone_params params = {
5021	.icp_opmode	= IEEE80211_M_STA,	/* default to station mode */
5022};
5023
5024static void
5025wlan_create(int s, struct ifreq *ifr)
5026{
5027	static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
5028
5029	if (params.icp_parent[0] == '\0')
5030		errx(1, "must specify a parent device (wlandev) when creating "
5031		    "a wlan device");
5032	if (params.icp_opmode == IEEE80211_M_WDS &&
5033	    memcmp(params.icp_bssid, zerobssid, sizeof(zerobssid)) == 0)
5034		errx(1, "no bssid specified for WDS (use wlanbssid)");
5035	ifr->ifr_data = (caddr_t) &params;
5036	if (ioctl(s, SIOCIFCREATE2, ifr) < 0)
5037		err(1, "SIOCIFCREATE2");
5038}
5039
5040static
5041DECL_CMD_FUNC(set80211clone_wlandev, arg, d)
5042{
5043	strlcpy(params.icp_parent, arg, IFNAMSIZ);
5044}
5045
5046static
5047DECL_CMD_FUNC(set80211clone_wlanbssid, arg, d)
5048{
5049	const struct ether_addr *ea;
5050
5051	ea = ether_aton(arg);
5052	if (ea == NULL)
5053		errx(1, "%s: cannot parse bssid", arg);
5054	memcpy(params.icp_bssid, ea->octet, IEEE80211_ADDR_LEN);
5055}
5056
5057static
5058DECL_CMD_FUNC(set80211clone_wlanaddr, arg, d)
5059{
5060	const struct ether_addr *ea;
5061
5062	ea = ether_aton(arg);
5063	if (ea == NULL)
5064		errx(1, "%s: cannot parse address", arg);
5065	memcpy(params.icp_macaddr, ea->octet, IEEE80211_ADDR_LEN);
5066	params.icp_flags |= IEEE80211_CLONE_MACADDR;
5067}
5068
5069static
5070DECL_CMD_FUNC(set80211clone_wlanmode, arg, d)
5071{
5072#define	iseq(a,b)	(strncasecmp(a,b,sizeof(b)-1) == 0)
5073	if (iseq(arg, "sta"))
5074		params.icp_opmode = IEEE80211_M_STA;
5075	else if (iseq(arg, "ahdemo") || iseq(arg, "adhoc-demo"))
5076		params.icp_opmode = IEEE80211_M_AHDEMO;
5077	else if (iseq(arg, "ibss") || iseq(arg, "adhoc"))
5078		params.icp_opmode = IEEE80211_M_IBSS;
5079	else if (iseq(arg, "ap") || iseq(arg, "host"))
5080		params.icp_opmode = IEEE80211_M_HOSTAP;
5081	else if (iseq(arg, "wds"))
5082		params.icp_opmode = IEEE80211_M_WDS;
5083	else if (iseq(arg, "monitor"))
5084		params.icp_opmode = IEEE80211_M_MONITOR;
5085	else if (iseq(arg, "tdma")) {
5086		params.icp_opmode = IEEE80211_M_AHDEMO;
5087		params.icp_flags |= IEEE80211_CLONE_TDMA;
5088	} else if (iseq(arg, "mesh") || iseq(arg, "mp")) /* mesh point */
5089		params.icp_opmode = IEEE80211_M_MBSS;
5090	else
5091		errx(1, "Don't know to create %s for %s", arg, name);
5092#undef iseq
5093}
5094
5095static void
5096set80211clone_beacons(const char *val, int d, int s, const struct afswtch *rafp)
5097{
5098	/* NB: inverted sense */
5099	if (d)
5100		params.icp_flags &= ~IEEE80211_CLONE_NOBEACONS;
5101	else
5102		params.icp_flags |= IEEE80211_CLONE_NOBEACONS;
5103}
5104
5105static void
5106set80211clone_bssid(const char *val, int d, int s, const struct afswtch *rafp)
5107{
5108	if (d)
5109		params.icp_flags |= IEEE80211_CLONE_BSSID;
5110	else
5111		params.icp_flags &= ~IEEE80211_CLONE_BSSID;
5112}
5113
5114static void
5115set80211clone_wdslegacy(const char *val, int d, int s, const struct afswtch *rafp)
5116{
5117	if (d)
5118		params.icp_flags |= IEEE80211_CLONE_WDSLEGACY;
5119	else
5120		params.icp_flags &= ~IEEE80211_CLONE_WDSLEGACY;
5121}
5122
5123static struct cmd ieee80211_cmds[] = {
5124	DEF_CMD_ARG("ssid",		set80211ssid),
5125	DEF_CMD_ARG("nwid",		set80211ssid),
5126	DEF_CMD_ARG("meshid",		set80211meshid),
5127	DEF_CMD_ARG("stationname",	set80211stationname),
5128	DEF_CMD_ARG("station",		set80211stationname),	/* BSD/OS */
5129	DEF_CMD_ARG("channel",		set80211channel),
5130	DEF_CMD_ARG("authmode",		set80211authmode),
5131	DEF_CMD_ARG("powersavemode",	set80211powersavemode),
5132	DEF_CMD("powersave",	1,	set80211powersave),
5133	DEF_CMD("-powersave",	0,	set80211powersave),
5134	DEF_CMD_ARG("powersavesleep", 	set80211powersavesleep),
5135	DEF_CMD_ARG("wepmode",		set80211wepmode),
5136	DEF_CMD("wep",		1,	set80211wep),
5137	DEF_CMD("-wep",		0,	set80211wep),
5138	DEF_CMD_ARG("deftxkey",		set80211weptxkey),
5139	DEF_CMD_ARG("weptxkey",		set80211weptxkey),
5140	DEF_CMD_ARG("wepkey",		set80211wepkey),
5141	DEF_CMD_ARG("nwkey",		set80211nwkey),		/* NetBSD */
5142	DEF_CMD("-nwkey",	0,	set80211wep),		/* NetBSD */
5143	DEF_CMD_ARG("rtsthreshold",	set80211rtsthreshold),
5144	DEF_CMD_ARG("protmode",		set80211protmode),
5145	DEF_CMD_ARG("txpower",		set80211txpower),
5146	DEF_CMD_ARG("roaming",		set80211roaming),
5147	DEF_CMD("wme",		1,	set80211wme),
5148	DEF_CMD("-wme",		0,	set80211wme),
5149	DEF_CMD("wmm",		1,	set80211wme),
5150	DEF_CMD("-wmm",		0,	set80211wme),
5151	DEF_CMD("hidessid",	1,	set80211hidessid),
5152	DEF_CMD("-hidessid",	0,	set80211hidessid),
5153	DEF_CMD("apbridge",	1,	set80211apbridge),
5154	DEF_CMD("-apbridge",	0,	set80211apbridge),
5155	DEF_CMD_ARG("chanlist",		set80211chanlist),
5156	DEF_CMD_ARG("bssid",		set80211bssid),
5157	DEF_CMD_ARG("ap",		set80211bssid),
5158	DEF_CMD("scan",	0,		set80211scan),
5159	DEF_CMD_ARG("list",		set80211list),
5160	DEF_CMD_ARG2("cwmin",		set80211cwmin),
5161	DEF_CMD_ARG2("cwmax",		set80211cwmax),
5162	DEF_CMD_ARG2("aifs",		set80211aifs),
5163	DEF_CMD_ARG2("txoplimit",	set80211txoplimit),
5164	DEF_CMD_ARG("acm",		set80211acm),
5165	DEF_CMD_ARG("-acm",		set80211noacm),
5166	DEF_CMD_ARG("ack",		set80211ackpolicy),
5167	DEF_CMD_ARG("-ack",		set80211noackpolicy),
5168	DEF_CMD_ARG2("bss:cwmin",	set80211bsscwmin),
5169	DEF_CMD_ARG2("bss:cwmax",	set80211bsscwmax),
5170	DEF_CMD_ARG2("bss:aifs",	set80211bssaifs),
5171	DEF_CMD_ARG2("bss:txoplimit",	set80211bsstxoplimit),
5172	DEF_CMD_ARG("dtimperiod",	set80211dtimperiod),
5173	DEF_CMD_ARG("bintval",		set80211bintval),
5174	DEF_CMD("mac:open",	IEEE80211_MACCMD_POLICY_OPEN,	set80211maccmd),
5175	DEF_CMD("mac:allow",	IEEE80211_MACCMD_POLICY_ALLOW,	set80211maccmd),
5176	DEF_CMD("mac:deny",	IEEE80211_MACCMD_POLICY_DENY,	set80211maccmd),
5177	DEF_CMD("mac:radius",	IEEE80211_MACCMD_POLICY_RADIUS,	set80211maccmd),
5178	DEF_CMD("mac:flush",	IEEE80211_MACCMD_FLUSH,		set80211maccmd),
5179	DEF_CMD("mac:detach",	IEEE80211_MACCMD_DETACH,	set80211maccmd),
5180	DEF_CMD_ARG("mac:add",		set80211addmac),
5181	DEF_CMD_ARG("mac:del",		set80211delmac),
5182	DEF_CMD_ARG("mac:kick",		set80211kickmac),
5183	DEF_CMD("pureg",	1,	set80211pureg),
5184	DEF_CMD("-pureg",	0,	set80211pureg),
5185	DEF_CMD("ff",		1,	set80211fastframes),
5186	DEF_CMD("-ff",		0,	set80211fastframes),
5187	DEF_CMD("dturbo",	1,	set80211dturbo),
5188	DEF_CMD("-dturbo",	0,	set80211dturbo),
5189	DEF_CMD("bgscan",	1,	set80211bgscan),
5190	DEF_CMD("-bgscan",	0,	set80211bgscan),
5191	DEF_CMD_ARG("bgscanidle",	set80211bgscanidle),
5192	DEF_CMD_ARG("bgscanintvl",	set80211bgscanintvl),
5193	DEF_CMD_ARG("scanvalid",	set80211scanvalid),
5194	DEF_CMD("quiet",        1,      set80211quiet),
5195	DEF_CMD("-quiet",       0,      set80211quiet),
5196	DEF_CMD_ARG("quiet_count",      set80211quietcount),
5197	DEF_CMD_ARG("quiet_period",     set80211quietperiod),
5198	DEF_CMD_ARG("quiet_dur",        set80211quietduration),
5199	DEF_CMD_ARG("quiet_offset",     set80211quietoffset),
5200	DEF_CMD_ARG("roam:rssi",	set80211roamrssi),
5201	DEF_CMD_ARG("roam:rate",	set80211roamrate),
5202	DEF_CMD_ARG("mcastrate",	set80211mcastrate),
5203	DEF_CMD_ARG("ucastrate",	set80211ucastrate),
5204	DEF_CMD_ARG("mgtrate",		set80211mgtrate),
5205	DEF_CMD_ARG("mgmtrate",		set80211mgtrate),
5206	DEF_CMD_ARG("maxretry",		set80211maxretry),
5207	DEF_CMD_ARG("fragthreshold",	set80211fragthreshold),
5208	DEF_CMD("burst",	1,	set80211burst),
5209	DEF_CMD("-burst",	0,	set80211burst),
5210	DEF_CMD_ARG("bmiss",		set80211bmissthreshold),
5211	DEF_CMD_ARG("bmissthreshold",	set80211bmissthreshold),
5212	DEF_CMD("shortgi",	1,	set80211shortgi),
5213	DEF_CMD("-shortgi",	0,	set80211shortgi),
5214	DEF_CMD("ampdurx",	2,	set80211ampdu),
5215	DEF_CMD("-ampdurx",	-2,	set80211ampdu),
5216	DEF_CMD("ampdutx",	1,	set80211ampdu),
5217	DEF_CMD("-ampdutx",	-1,	set80211ampdu),
5218	DEF_CMD("ampdu",	3,	set80211ampdu),		/* NB: tx+rx */
5219	DEF_CMD("-ampdu",	-3,	set80211ampdu),
5220	DEF_CMD_ARG("ampdulimit",	set80211ampdulimit),
5221	DEF_CMD_ARG("ampdudensity",	set80211ampdudensity),
5222	DEF_CMD("amsdurx",	2,	set80211amsdu),
5223	DEF_CMD("-amsdurx",	-2,	set80211amsdu),
5224	DEF_CMD("amsdutx",	1,	set80211amsdu),
5225	DEF_CMD("-amsdutx",	-1,	set80211amsdu),
5226	DEF_CMD("amsdu",	3,	set80211amsdu),		/* NB: tx+rx */
5227	DEF_CMD("-amsdu",	-3,	set80211amsdu),
5228	DEF_CMD_ARG("amsdulimit",	set80211amsdulimit),
5229	DEF_CMD("puren",	1,	set80211puren),
5230	DEF_CMD("-puren",	0,	set80211puren),
5231	DEF_CMD("doth",		1,	set80211doth),
5232	DEF_CMD("-doth",	0,	set80211doth),
5233	DEF_CMD("dfs",		1,	set80211dfs),
5234	DEF_CMD("-dfs",		0,	set80211dfs),
5235	DEF_CMD("htcompat",	1,	set80211htcompat),
5236	DEF_CMD("-htcompat",	0,	set80211htcompat),
5237	DEF_CMD("dwds",		1,	set80211dwds),
5238	DEF_CMD("-dwds",	0,	set80211dwds),
5239	DEF_CMD("inact",	1,	set80211inact),
5240	DEF_CMD("-inact",	0,	set80211inact),
5241	DEF_CMD("tsn",		1,	set80211tsn),
5242	DEF_CMD("-tsn",		0,	set80211tsn),
5243	DEF_CMD_ARG("regdomain",	set80211regdomain),
5244	DEF_CMD_ARG("country",		set80211country),
5245	DEF_CMD("indoor",	'I',	set80211location),
5246	DEF_CMD("-indoor",	'O',	set80211location),
5247	DEF_CMD("outdoor",	'O',	set80211location),
5248	DEF_CMD("-outdoor",	'I',	set80211location),
5249	DEF_CMD("anywhere",	' ',	set80211location),
5250	DEF_CMD("ecm",		1,	set80211ecm),
5251	DEF_CMD("-ecm",		0,	set80211ecm),
5252	DEF_CMD("dotd",		1,	set80211dotd),
5253	DEF_CMD("-dotd",	0,	set80211dotd),
5254	DEF_CMD_ARG("htprotmode",	set80211htprotmode),
5255	DEF_CMD("ht20",		1,	set80211htconf),
5256	DEF_CMD("-ht20",	0,	set80211htconf),
5257	DEF_CMD("ht40",		3,	set80211htconf),	/* NB: 20+40 */
5258	DEF_CMD("-ht40",	0,	set80211htconf),
5259	DEF_CMD("ht",		3,	set80211htconf),	/* NB: 20+40 */
5260	DEF_CMD("-ht",		0,	set80211htconf),
5261	DEF_CMD("rifs",		1,	set80211rifs),
5262	DEF_CMD("-rifs",	0,	set80211rifs),
5263	DEF_CMD("smps",		IEEE80211_HTCAP_SMPS_ENA,	set80211smps),
5264	DEF_CMD("smpsdyn",	IEEE80211_HTCAP_SMPS_DYNAMIC,	set80211smps),
5265	DEF_CMD("-smps",	IEEE80211_HTCAP_SMPS_OFF,	set80211smps),
5266	/* XXX for testing */
5267	DEF_CMD_ARG("chanswitch",	set80211chanswitch),
5268
5269	DEF_CMD_ARG("tdmaslot",		set80211tdmaslot),
5270	DEF_CMD_ARG("tdmaslotcnt",	set80211tdmaslotcnt),
5271	DEF_CMD_ARG("tdmaslotlen",	set80211tdmaslotlen),
5272	DEF_CMD_ARG("tdmabintval",	set80211tdmabintval),
5273
5274	DEF_CMD_ARG("meshttl",		set80211meshttl),
5275	DEF_CMD("meshforward",	1,	set80211meshforward),
5276	DEF_CMD("-meshforward",	0,	set80211meshforward),
5277	DEF_CMD("meshpeering",	1,	set80211meshpeering),
5278	DEF_CMD("-meshpeering",	0,	set80211meshpeering),
5279	DEF_CMD_ARG("meshmetric",	set80211meshmetric),
5280	DEF_CMD_ARG("meshpath",		set80211meshpath),
5281	DEF_CMD("meshrt:flush",	IEEE80211_MESH_RTCMD_FLUSH,	set80211meshrtcmd),
5282	DEF_CMD_ARG("meshrt:add",	set80211addmeshrt),
5283	DEF_CMD_ARG("meshrt:del",	set80211delmeshrt),
5284	DEF_CMD_ARG("hwmprootmode",	set80211hwmprootmode),
5285	DEF_CMD_ARG("hwmpmaxhops",	set80211hwmpmaxhops),
5286
5287	/* vap cloning support */
5288	DEF_CLONE_CMD_ARG("wlanaddr",	set80211clone_wlanaddr),
5289	DEF_CLONE_CMD_ARG("wlanbssid",	set80211clone_wlanbssid),
5290	DEF_CLONE_CMD_ARG("wlandev",	set80211clone_wlandev),
5291	DEF_CLONE_CMD_ARG("wlanmode",	set80211clone_wlanmode),
5292	DEF_CLONE_CMD("beacons", 1,	set80211clone_beacons),
5293	DEF_CLONE_CMD("-beacons", 0,	set80211clone_beacons),
5294	DEF_CLONE_CMD("bssid",	1,	set80211clone_bssid),
5295	DEF_CLONE_CMD("-bssid",	0,	set80211clone_bssid),
5296	DEF_CLONE_CMD("wdslegacy", 1,	set80211clone_wdslegacy),
5297	DEF_CLONE_CMD("-wdslegacy", 0,	set80211clone_wdslegacy),
5298};
5299static struct afswtch af_ieee80211 = {
5300	.af_name	= "af_ieee80211",
5301	.af_af		= AF_UNSPEC,
5302	.af_other_status = ieee80211_status,
5303};
5304
5305static __constructor void
5306ieee80211_ctor(void)
5307{
5308#define	N(a)	(sizeof(a) / sizeof(a[0]))
5309	int i;
5310
5311	for (i = 0; i < N(ieee80211_cmds);  i++)
5312		cmd_register(&ieee80211_cmds[i]);
5313	af_register(&af_ieee80211);
5314	clone_setdefcallback("wlan", wlan_create);
5315#undef N
5316}
5317