ifieee80211.c revision 224224
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 224224 2011-07-20 05:59:28Z adrian $
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 compatability 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
1340set80211bgscan(const char *val, int d, int s, const struct afswtch *rafp)
1341{
1342	set80211(s, IEEE80211_IOC_BGSCAN, d, 0, NULL);
1343}
1344
1345static
1346DECL_CMD_FUNC(set80211bgscanidle, val, d)
1347{
1348	set80211(s, IEEE80211_IOC_BGSCAN_IDLE, atoi(val), 0, NULL);
1349}
1350
1351static
1352DECL_CMD_FUNC(set80211bgscanintvl, val, d)
1353{
1354	set80211(s, IEEE80211_IOC_BGSCAN_INTERVAL, atoi(val), 0, NULL);
1355}
1356
1357static
1358DECL_CMD_FUNC(set80211scanvalid, val, d)
1359{
1360	set80211(s, IEEE80211_IOC_SCANVALID, atoi(val), 0, NULL);
1361}
1362
1363/*
1364 * Parse an optional trailing specification of which netbands
1365 * to apply a parameter to.  This is basically the same syntax
1366 * as used for channels but you can concatenate to specify
1367 * multiple.  For example:
1368 *	14:abg		apply to 11a, 11b, and 11g
1369 *	6:ht		apply to 11na and 11ng
1370 * We don't make a big effort to catch silly things; this is
1371 * really a convenience mechanism.
1372 */
1373static int
1374getmodeflags(const char *val)
1375{
1376	const char *cp;
1377	int flags;
1378
1379	flags = 0;
1380
1381	cp = strchr(val, ':');
1382	if (cp != NULL) {
1383		for (cp++; isalpha((int) *cp); cp++) {
1384			/* accept mixed case */
1385			int c = *cp;
1386			if (isupper(c))
1387				c = tolower(c);
1388			switch (c) {
1389			case 'a':		/* 802.11a */
1390				flags |= IEEE80211_CHAN_A;
1391				break;
1392			case 'b':		/* 802.11b */
1393				flags |= IEEE80211_CHAN_B;
1394				break;
1395			case 'g':		/* 802.11g */
1396				flags |= IEEE80211_CHAN_G;
1397				break;
1398			case 'n':		/* 802.11n */
1399				flags |= IEEE80211_CHAN_HT;
1400				break;
1401			case 'd':		/* dt = Atheros Dynamic Turbo */
1402				flags |= IEEE80211_CHAN_TURBO;
1403				break;
1404			case 't':		/* ht, dt, st, t */
1405				/* dt and unadorned t specify Dynamic Turbo */
1406				if ((flags & (IEEE80211_CHAN_STURBO|IEEE80211_CHAN_HT)) == 0)
1407					flags |= IEEE80211_CHAN_TURBO;
1408				break;
1409			case 's':		/* st = Atheros Static Turbo */
1410				flags |= IEEE80211_CHAN_STURBO;
1411				break;
1412			case 'h':		/* 1/2-width channels */
1413				flags |= IEEE80211_CHAN_HALF;
1414				break;
1415			case 'q':		/* 1/4-width channels */
1416				flags |= IEEE80211_CHAN_QUARTER;
1417				break;
1418			default:
1419				errx(-1, "%s: Invalid mode attribute %c\n",
1420				    val, *cp);
1421			}
1422		}
1423	}
1424	return flags;
1425}
1426
1427#define	IEEE80211_CHAN_HTA	(IEEE80211_CHAN_HT|IEEE80211_CHAN_5GHZ)
1428#define	IEEE80211_CHAN_HTG	(IEEE80211_CHAN_HT|IEEE80211_CHAN_2GHZ)
1429
1430#define	_APPLY(_flags, _base, _param, _v) do {				\
1431    if (_flags & IEEE80211_CHAN_HT) {					\
1432	    if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
1433		    _base.params[IEEE80211_MODE_11NA]._param = _v;	\
1434		    _base.params[IEEE80211_MODE_11NG]._param = _v;	\
1435	    } else if (_flags & IEEE80211_CHAN_5GHZ)			\
1436		    _base.params[IEEE80211_MODE_11NA]._param = _v;	\
1437	    else							\
1438		    _base.params[IEEE80211_MODE_11NG]._param = _v;	\
1439    }									\
1440    if (_flags & IEEE80211_CHAN_TURBO) {				\
1441	    if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
1442		    _base.params[IEEE80211_MODE_TURBO_A]._param = _v;	\
1443		    _base.params[IEEE80211_MODE_TURBO_G]._param = _v;	\
1444	    } else if (_flags & IEEE80211_CHAN_5GHZ)			\
1445		    _base.params[IEEE80211_MODE_TURBO_A]._param = _v;	\
1446	    else							\
1447		    _base.params[IEEE80211_MODE_TURBO_G]._param = _v;	\
1448    }									\
1449    if (_flags & IEEE80211_CHAN_STURBO)					\
1450	    _base.params[IEEE80211_MODE_STURBO_A]._param = _v;		\
1451    if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)		\
1452	    _base.params[IEEE80211_MODE_11A]._param = _v;		\
1453    if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)		\
1454	    _base.params[IEEE80211_MODE_11G]._param = _v;		\
1455    if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)		\
1456	    _base.params[IEEE80211_MODE_11B]._param = _v;		\
1457    if (_flags & IEEE80211_CHAN_HALF)					\
1458	    _base.params[IEEE80211_MODE_HALF]._param = _v;		\
1459    if (_flags & IEEE80211_CHAN_QUARTER)				\
1460	    _base.params[IEEE80211_MODE_QUARTER]._param = _v;		\
1461} while (0)
1462#define	_APPLY1(_flags, _base, _param, _v) do {				\
1463    if (_flags & IEEE80211_CHAN_HT) {					\
1464	    if (_flags & IEEE80211_CHAN_5GHZ)				\
1465		    _base.params[IEEE80211_MODE_11NA]._param = _v;	\
1466	    else							\
1467		    _base.params[IEEE80211_MODE_11NG]._param = _v;	\
1468    } else if ((_flags & IEEE80211_CHAN_108A) == IEEE80211_CHAN_108A)	\
1469	    _base.params[IEEE80211_MODE_TURBO_A]._param = _v;		\
1470    else if ((_flags & IEEE80211_CHAN_108G) == IEEE80211_CHAN_108G)	\
1471	    _base.params[IEEE80211_MODE_TURBO_G]._param = _v;		\
1472    else if ((_flags & IEEE80211_CHAN_ST) == IEEE80211_CHAN_ST)		\
1473	    _base.params[IEEE80211_MODE_STURBO_A]._param = _v;		\
1474    else if (_flags & IEEE80211_CHAN_HALF)				\
1475	    _base.params[IEEE80211_MODE_HALF]._param = _v;		\
1476    else if (_flags & IEEE80211_CHAN_QUARTER)				\
1477	    _base.params[IEEE80211_MODE_QUARTER]._param = _v;		\
1478    else if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)		\
1479	    _base.params[IEEE80211_MODE_11A]._param = _v;		\
1480    else if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)		\
1481	    _base.params[IEEE80211_MODE_11G]._param = _v;		\
1482    else if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)		\
1483	    _base.params[IEEE80211_MODE_11B]._param = _v;		\
1484} while (0)
1485#define	_APPLY_RATE(_flags, _base, _param, _v) do {			\
1486    if (_flags & IEEE80211_CHAN_HT) {					\
1487	(_v) = (_v / 2) | IEEE80211_RATE_MCS;				\
1488    }									\
1489    _APPLY(_flags, _base, _param, _v);					\
1490} while (0)
1491#define	_APPLY_RATE1(_flags, _base, _param, _v) do {			\
1492    if (_flags & IEEE80211_CHAN_HT) {					\
1493	(_v) = (_v / 2) | IEEE80211_RATE_MCS;				\
1494    }									\
1495    _APPLY1(_flags, _base, _param, _v);					\
1496} while (0)
1497
1498static
1499DECL_CMD_FUNC(set80211roamrssi, val, d)
1500{
1501	double v = atof(val);
1502	int rssi, flags;
1503
1504	rssi = (int) (2*v);
1505	if (rssi != 2*v)
1506		errx(-1, "invalid rssi (must be .5 dBm units)");
1507	flags = getmodeflags(val);
1508	getroam(s);
1509	if (flags == 0) {		/* NB: no flags => current channel */
1510		flags = getcurchan(s)->ic_flags;
1511		_APPLY1(flags, roamparams, rssi, rssi);
1512	} else
1513		_APPLY(flags, roamparams, rssi, rssi);
1514	callback_register(setroam_cb, &roamparams);
1515}
1516
1517static int
1518getrate(const char *val, const char *tag)
1519{
1520	double v = atof(val);
1521	int rate;
1522
1523	rate = (int) (2*v);
1524	if (rate != 2*v)
1525		errx(-1, "invalid %s rate (must be .5 Mb/s units)", tag);
1526	return rate;		/* NB: returns 2x the specified value */
1527}
1528
1529static
1530DECL_CMD_FUNC(set80211roamrate, val, d)
1531{
1532	int rate, flags;
1533
1534	rate = getrate(val, "roam");
1535	flags = getmodeflags(val);
1536	getroam(s);
1537	if (flags == 0) {		/* NB: no flags => current channel */
1538		flags = getcurchan(s)->ic_flags;
1539		_APPLY_RATE1(flags, roamparams, rate, rate);
1540	} else
1541		_APPLY_RATE(flags, roamparams, rate, rate);
1542	callback_register(setroam_cb, &roamparams);
1543}
1544
1545static
1546DECL_CMD_FUNC(set80211mcastrate, val, d)
1547{
1548	int rate, flags;
1549
1550	rate = getrate(val, "mcast");
1551	flags = getmodeflags(val);
1552	gettxparams(s);
1553	if (flags == 0) {		/* NB: no flags => current channel */
1554		flags = getcurchan(s)->ic_flags;
1555		_APPLY_RATE1(flags, txparams, mcastrate, rate);
1556	} else
1557		_APPLY_RATE(flags, txparams, mcastrate, rate);
1558	callback_register(settxparams_cb, &txparams);
1559}
1560
1561static
1562DECL_CMD_FUNC(set80211mgtrate, val, d)
1563{
1564	int rate, flags;
1565
1566	rate = getrate(val, "mgmt");
1567	flags = getmodeflags(val);
1568	gettxparams(s);
1569	if (flags == 0) {		/* NB: no flags => current channel */
1570		flags = getcurchan(s)->ic_flags;
1571		_APPLY_RATE1(flags, txparams, mgmtrate, rate);
1572	} else
1573		_APPLY_RATE(flags, txparams, mgmtrate, rate);
1574	callback_register(settxparams_cb, &txparams);
1575}
1576
1577static
1578DECL_CMD_FUNC(set80211ucastrate, val, d)
1579{
1580	int flags;
1581
1582	gettxparams(s);
1583	flags = getmodeflags(val);
1584	if (isanyarg(val)) {
1585		if (flags == 0) {	/* NB: no flags => current channel */
1586			flags = getcurchan(s)->ic_flags;
1587			_APPLY1(flags, txparams, ucastrate,
1588			    IEEE80211_FIXED_RATE_NONE);
1589		} else
1590			_APPLY(flags, txparams, ucastrate,
1591			    IEEE80211_FIXED_RATE_NONE);
1592	} else {
1593		int rate = getrate(val, "ucast");
1594		if (flags == 0) {	/* NB: no flags => current channel */
1595			flags = getcurchan(s)->ic_flags;
1596			_APPLY_RATE1(flags, txparams, ucastrate, rate);
1597		} else
1598			_APPLY_RATE(flags, txparams, ucastrate, rate);
1599	}
1600	callback_register(settxparams_cb, &txparams);
1601}
1602
1603static
1604DECL_CMD_FUNC(set80211maxretry, val, d)
1605{
1606	int v = atoi(val), flags;
1607
1608	flags = getmodeflags(val);
1609	gettxparams(s);
1610	if (flags == 0) {		/* NB: no flags => current channel */
1611		flags = getcurchan(s)->ic_flags;
1612		_APPLY1(flags, txparams, maxretry, v);
1613	} else
1614		_APPLY(flags, txparams, maxretry, v);
1615	callback_register(settxparams_cb, &txparams);
1616}
1617#undef _APPLY_RATE
1618#undef _APPLY
1619#undef IEEE80211_CHAN_HTA
1620#undef IEEE80211_CHAN_HTG
1621
1622static
1623DECL_CMD_FUNC(set80211fragthreshold, val, d)
1624{
1625	set80211(s, IEEE80211_IOC_FRAGTHRESHOLD,
1626		isundefarg(val) ? IEEE80211_FRAG_MAX : atoi(val), 0, NULL);
1627}
1628
1629static
1630DECL_CMD_FUNC(set80211bmissthreshold, val, d)
1631{
1632	set80211(s, IEEE80211_IOC_BMISSTHRESHOLD,
1633		isundefarg(val) ? IEEE80211_HWBMISS_MAX : atoi(val), 0, NULL);
1634}
1635
1636static void
1637set80211burst(const char *val, int d, int s, const struct afswtch *rafp)
1638{
1639	set80211(s, IEEE80211_IOC_BURST, d, 0, NULL);
1640}
1641
1642static void
1643set80211doth(const char *val, int d, int s, const struct afswtch *rafp)
1644{
1645	set80211(s, IEEE80211_IOC_DOTH, d, 0, NULL);
1646}
1647
1648static void
1649set80211dfs(const char *val, int d, int s, const struct afswtch *rafp)
1650{
1651	set80211(s, IEEE80211_IOC_DFS, d, 0, NULL);
1652}
1653
1654static void
1655set80211shortgi(const char *val, int d, int s, const struct afswtch *rafp)
1656{
1657	set80211(s, IEEE80211_IOC_SHORTGI,
1658		d ? (IEEE80211_HTCAP_SHORTGI20 | IEEE80211_HTCAP_SHORTGI40) : 0,
1659		0, NULL);
1660}
1661
1662static void
1663set80211ampdu(const char *val, int d, int s, const struct afswtch *rafp)
1664{
1665	int ampdu;
1666
1667	if (get80211val(s, IEEE80211_IOC_AMPDU, &ampdu) < 0)
1668		errx(-1, "cannot get AMPDU setting");
1669	if (d < 0) {
1670		d = -d;
1671		ampdu &= ~d;
1672	} else
1673		ampdu |= d;
1674	set80211(s, IEEE80211_IOC_AMPDU, ampdu, 0, NULL);
1675}
1676
1677static
1678DECL_CMD_FUNC(set80211ampdulimit, val, d)
1679{
1680	int v;
1681
1682	switch (atoi(val)) {
1683	case 8:
1684	case 8*1024:
1685		v = IEEE80211_HTCAP_MAXRXAMPDU_8K;
1686		break;
1687	case 16:
1688	case 16*1024:
1689		v = IEEE80211_HTCAP_MAXRXAMPDU_16K;
1690		break;
1691	case 32:
1692	case 32*1024:
1693		v = IEEE80211_HTCAP_MAXRXAMPDU_32K;
1694		break;
1695	case 64:
1696	case 64*1024:
1697		v = IEEE80211_HTCAP_MAXRXAMPDU_64K;
1698		break;
1699	default:
1700		errx(-1, "invalid A-MPDU limit %s", val);
1701	}
1702	set80211(s, IEEE80211_IOC_AMPDU_LIMIT, v, 0, NULL);
1703}
1704
1705static
1706DECL_CMD_FUNC(set80211ampdudensity, val, d)
1707{
1708	int v;
1709
1710	if (isanyarg(val) || strcasecmp(val, "na") == 0)
1711		v = IEEE80211_HTCAP_MPDUDENSITY_NA;
1712	else switch ((int)(atof(val)*4)) {
1713	case 0:
1714		v = IEEE80211_HTCAP_MPDUDENSITY_NA;
1715		break;
1716	case 1:
1717		v = IEEE80211_HTCAP_MPDUDENSITY_025;
1718		break;
1719	case 2:
1720		v = IEEE80211_HTCAP_MPDUDENSITY_05;
1721		break;
1722	case 4:
1723		v = IEEE80211_HTCAP_MPDUDENSITY_1;
1724		break;
1725	case 8:
1726		v = IEEE80211_HTCAP_MPDUDENSITY_2;
1727		break;
1728	case 16:
1729		v = IEEE80211_HTCAP_MPDUDENSITY_4;
1730		break;
1731	case 32:
1732		v = IEEE80211_HTCAP_MPDUDENSITY_8;
1733		break;
1734	case 64:
1735		v = IEEE80211_HTCAP_MPDUDENSITY_16;
1736		break;
1737	default:
1738		errx(-1, "invalid A-MPDU density %s", val);
1739	}
1740	set80211(s, IEEE80211_IOC_AMPDU_DENSITY, v, 0, NULL);
1741}
1742
1743static void
1744set80211amsdu(const char *val, int d, int s, const struct afswtch *rafp)
1745{
1746	int amsdu;
1747
1748	if (get80211val(s, IEEE80211_IOC_AMSDU, &amsdu) < 0)
1749		err(-1, "cannot get AMSDU setting");
1750	if (d < 0) {
1751		d = -d;
1752		amsdu &= ~d;
1753	} else
1754		amsdu |= d;
1755	set80211(s, IEEE80211_IOC_AMSDU, amsdu, 0, NULL);
1756}
1757
1758static
1759DECL_CMD_FUNC(set80211amsdulimit, val, d)
1760{
1761	set80211(s, IEEE80211_IOC_AMSDU_LIMIT, atoi(val), 0, NULL);
1762}
1763
1764static void
1765set80211puren(const char *val, int d, int s, const struct afswtch *rafp)
1766{
1767	set80211(s, IEEE80211_IOC_PUREN, d, 0, NULL);
1768}
1769
1770static void
1771set80211htcompat(const char *val, int d, int s, const struct afswtch *rafp)
1772{
1773	set80211(s, IEEE80211_IOC_HTCOMPAT, d, 0, NULL);
1774}
1775
1776static void
1777set80211htconf(const char *val, int d, int s, const struct afswtch *rafp)
1778{
1779	set80211(s, IEEE80211_IOC_HTCONF, d, 0, NULL);
1780	htconf = d;
1781}
1782
1783static void
1784set80211dwds(const char *val, int d, int s, const struct afswtch *rafp)
1785{
1786	set80211(s, IEEE80211_IOC_DWDS, d, 0, NULL);
1787}
1788
1789static void
1790set80211inact(const char *val, int d, int s, const struct afswtch *rafp)
1791{
1792	set80211(s, IEEE80211_IOC_INACTIVITY, d, 0, NULL);
1793}
1794
1795static void
1796set80211tsn(const char *val, int d, int s, const struct afswtch *rafp)
1797{
1798	set80211(s, IEEE80211_IOC_TSN, d, 0, NULL);
1799}
1800
1801static void
1802set80211dotd(const char *val, int d, int s, const struct afswtch *rafp)
1803{
1804	set80211(s, IEEE80211_IOC_DOTD, d, 0, NULL);
1805}
1806
1807static void
1808set80211smps(const char *val, int d, int s, const struct afswtch *rafp)
1809{
1810	set80211(s, IEEE80211_IOC_SMPS, d, 0, NULL);
1811}
1812
1813static void
1814set80211rifs(const char *val, int d, int s, const struct afswtch *rafp)
1815{
1816	set80211(s, IEEE80211_IOC_RIFS, d, 0, NULL);
1817}
1818
1819static
1820DECL_CMD_FUNC(set80211tdmaslot, val, d)
1821{
1822	set80211(s, IEEE80211_IOC_TDMA_SLOT, atoi(val), 0, NULL);
1823}
1824
1825static
1826DECL_CMD_FUNC(set80211tdmaslotcnt, val, d)
1827{
1828	set80211(s, IEEE80211_IOC_TDMA_SLOTCNT, atoi(val), 0, NULL);
1829}
1830
1831static
1832DECL_CMD_FUNC(set80211tdmaslotlen, val, d)
1833{
1834	set80211(s, IEEE80211_IOC_TDMA_SLOTLEN, atoi(val), 0, NULL);
1835}
1836
1837static
1838DECL_CMD_FUNC(set80211tdmabintval, val, d)
1839{
1840	set80211(s, IEEE80211_IOC_TDMA_BINTERVAL, atoi(val), 0, NULL);
1841}
1842
1843static
1844DECL_CMD_FUNC(set80211meshttl, val, d)
1845{
1846	set80211(s, IEEE80211_IOC_MESH_TTL, atoi(val), 0, NULL);
1847}
1848
1849static
1850DECL_CMD_FUNC(set80211meshforward, val, d)
1851{
1852	set80211(s, IEEE80211_IOC_MESH_FWRD, atoi(val), 0, NULL);
1853}
1854
1855static
1856DECL_CMD_FUNC(set80211meshpeering, val, d)
1857{
1858	set80211(s, IEEE80211_IOC_MESH_AP, atoi(val), 0, NULL);
1859}
1860
1861static
1862DECL_CMD_FUNC(set80211meshmetric, val, d)
1863{
1864	char v[12];
1865
1866	memcpy(v, val, sizeof(v));
1867	set80211(s, IEEE80211_IOC_MESH_PR_METRIC, 0, 0, v);
1868}
1869
1870static
1871DECL_CMD_FUNC(set80211meshpath, val, d)
1872{
1873	char v[12];
1874
1875	memcpy(v, val, sizeof(v));
1876	set80211(s, IEEE80211_IOC_MESH_PR_PATH, 0, 0, v);
1877}
1878
1879static int
1880regdomain_sort(const void *a, const void *b)
1881{
1882#define	CHAN_ALL \
1883	(IEEE80211_CHAN_ALLTURBO|IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER)
1884	const struct ieee80211_channel *ca = a;
1885	const struct ieee80211_channel *cb = b;
1886
1887	return ca->ic_freq == cb->ic_freq ?
1888	    (ca->ic_flags & CHAN_ALL) - (cb->ic_flags & CHAN_ALL) :
1889	    ca->ic_freq - cb->ic_freq;
1890#undef CHAN_ALL
1891}
1892
1893static const struct ieee80211_channel *
1894chanlookup(const struct ieee80211_channel chans[], int nchans,
1895	int freq, int flags)
1896{
1897	int i;
1898
1899	flags &= IEEE80211_CHAN_ALLTURBO;
1900	for (i = 0; i < nchans; i++) {
1901		const struct ieee80211_channel *c = &chans[i];
1902		if (c->ic_freq == freq &&
1903		    (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
1904			return c;
1905	}
1906	return NULL;
1907}
1908
1909static int
1910chanfind(const struct ieee80211_channel chans[], int nchans, int flags)
1911{
1912	int i;
1913
1914	for (i = 0; i < nchans; i++) {
1915		const struct ieee80211_channel *c = &chans[i];
1916		if ((c->ic_flags & flags) == flags)
1917			return 1;
1918	}
1919	return 0;
1920}
1921
1922/*
1923 * Check channel compatibility.
1924 */
1925static int
1926checkchan(const struct ieee80211req_chaninfo *avail, int freq, int flags)
1927{
1928	flags &= ~REQ_FLAGS;
1929	/*
1930	 * Check if exact channel is in the calibration table;
1931	 * everything below is to deal with channels that we
1932	 * want to include but that are not explicitly listed.
1933	 */
1934	if (flags & IEEE80211_CHAN_HT40) {
1935		/* NB: we use an HT40 channel center that matches HT20 */
1936		flags = (flags &~ IEEE80211_CHAN_HT40) | IEEE80211_CHAN_HT20;
1937	}
1938	if (chanlookup(avail->ic_chans, avail->ic_nchans, freq, flags) != NULL)
1939		return 1;
1940	if (flags & IEEE80211_CHAN_GSM) {
1941		/*
1942		 * XXX GSM frequency mapping is handled in the kernel
1943		 * so we cannot find them in the calibration table;
1944		 * just accept the channel and the kernel will reject
1945		 * the channel list if it's wrong.
1946		 */
1947		return 1;
1948	}
1949	/*
1950	 * If this is a 1/2 or 1/4 width channel allow it if a full
1951	 * width channel is present for this frequency, and the device
1952	 * supports fractional channels on this band.  This is a hack
1953	 * that avoids bloating the calibration table; it may be better
1954	 * by per-band attributes though (we are effectively calculating
1955	 * this attribute by scanning the channel list ourself).
1956	 */
1957	if ((flags & (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == 0)
1958		return 0;
1959	if (chanlookup(avail->ic_chans, avail->ic_nchans, freq,
1960	    flags &~ (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == NULL)
1961		return 0;
1962	if (flags & IEEE80211_CHAN_HALF) {
1963		return chanfind(avail->ic_chans, avail->ic_nchans,
1964		    IEEE80211_CHAN_HALF |
1965		       (flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
1966	} else {
1967		return chanfind(avail->ic_chans, avail->ic_nchans,
1968		    IEEE80211_CHAN_QUARTER |
1969			(flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
1970	}
1971}
1972
1973static void
1974regdomain_addchans(struct ieee80211req_chaninfo *ci,
1975	const netband_head *bands,
1976	const struct ieee80211_regdomain *reg,
1977	uint32_t chanFlags,
1978	const struct ieee80211req_chaninfo *avail)
1979{
1980	const struct netband *nb;
1981	const struct freqband *b;
1982	struct ieee80211_channel *c, *prev;
1983	int freq, hi_adj, lo_adj, channelSep;
1984	uint32_t flags;
1985
1986	hi_adj = (chanFlags & IEEE80211_CHAN_HT40U) ? -20 : 0;
1987	lo_adj = (chanFlags & IEEE80211_CHAN_HT40D) ? 20 : 0;
1988	channelSep = (chanFlags & IEEE80211_CHAN_2GHZ) ? 0 : 40;
1989	LIST_FOREACH(nb, bands, next) {
1990		b = nb->band;
1991		if (verbose) {
1992			printf("%s:", __func__);
1993			printb(" chanFlags", chanFlags, IEEE80211_CHAN_BITS);
1994			printb(" bandFlags", nb->flags | b->flags,
1995			    IEEE80211_CHAN_BITS);
1996			putchar('\n');
1997		}
1998		prev = NULL;
1999		for (freq = b->freqStart + lo_adj;
2000		     freq <= b->freqEnd + hi_adj; freq += b->chanSep) {
2001			/*
2002			 * Construct flags for the new channel.  We take
2003			 * the attributes from the band descriptions except
2004			 * for HT40 which is enabled generically (i.e. +/-
2005			 * extension channel) in the band description and
2006			 * then constrained according by channel separation.
2007			 */
2008			flags = nb->flags | b->flags;
2009			if (flags & IEEE80211_CHAN_HT) {
2010				/*
2011				 * HT channels are generated specially; we're
2012				 * called to add HT20, HT40+, and HT40- chan's
2013				 * so we need to expand only band specs for
2014				 * the HT channel type being added.
2015				 */
2016				if ((chanFlags & IEEE80211_CHAN_HT20) &&
2017				    (flags & IEEE80211_CHAN_HT20) == 0) {
2018					if (verbose)
2019						printf("%u: skip, not an "
2020						    "HT20 channel\n", freq);
2021					continue;
2022				}
2023				if ((chanFlags & IEEE80211_CHAN_HT40) &&
2024				    (flags & IEEE80211_CHAN_HT40) == 0) {
2025					if (verbose)
2026						printf("%u: skip, not an "
2027						    "HT40 channel\n", freq);
2028					continue;
2029				}
2030				/* NB: HT attribute comes from caller */
2031				flags &= ~IEEE80211_CHAN_HT;
2032				flags |= chanFlags & IEEE80211_CHAN_HT;
2033			}
2034			/*
2035			 * Check if device can operate on this frequency.
2036			 */
2037			if (!checkchan(avail, freq, flags)) {
2038				if (verbose) {
2039					printf("%u: skip, ", freq);
2040					printb("flags", flags,
2041					    IEEE80211_CHAN_BITS);
2042					printf(" not available\n");
2043				}
2044				continue;
2045			}
2046			if ((flags & REQ_ECM) && !reg->ecm) {
2047				if (verbose)
2048					printf("%u: skip, ECM channel\n", freq);
2049				continue;
2050			}
2051			if ((flags & REQ_INDOOR) && reg->location == 'O') {
2052				if (verbose)
2053					printf("%u: skip, indoor channel\n",
2054					    freq);
2055				continue;
2056			}
2057			if ((flags & REQ_OUTDOOR) && reg->location == 'I') {
2058				if (verbose)
2059					printf("%u: skip, outdoor channel\n",
2060					    freq);
2061				continue;
2062			}
2063			if ((flags & IEEE80211_CHAN_HT40) &&
2064			    prev != NULL && (freq - prev->ic_freq) < channelSep) {
2065				if (verbose)
2066					printf("%u: skip, only %u channel "
2067					    "separation, need %d\n", freq,
2068					    freq - prev->ic_freq, channelSep);
2069				continue;
2070			}
2071			if (ci->ic_nchans == IEEE80211_CHAN_MAX) {
2072				if (verbose)
2073					printf("%u: skip, channel table full\n",
2074					    freq);
2075				break;
2076			}
2077			c = &ci->ic_chans[ci->ic_nchans++];
2078			memset(c, 0, sizeof(*c));
2079			c->ic_freq = freq;
2080			c->ic_flags = flags;
2081			if (c->ic_flags & IEEE80211_CHAN_DFS)
2082				c->ic_maxregpower = nb->maxPowerDFS;
2083			else
2084				c->ic_maxregpower = nb->maxPower;
2085			if (verbose) {
2086				printf("[%3d] add freq %u ",
2087				    ci->ic_nchans-1, c->ic_freq);
2088				printb("flags", c->ic_flags, IEEE80211_CHAN_BITS);
2089				printf(" power %u\n", c->ic_maxregpower);
2090			}
2091			/* NB: kernel fills in other fields */
2092			prev = c;
2093		}
2094	}
2095}
2096
2097static void
2098regdomain_makechannels(
2099	struct ieee80211_regdomain_req *req,
2100	const struct ieee80211_devcaps_req *dc)
2101{
2102	struct regdata *rdp = getregdata();
2103	const struct country *cc;
2104	const struct ieee80211_regdomain *reg = &req->rd;
2105	struct ieee80211req_chaninfo *ci = &req->chaninfo;
2106	const struct regdomain *rd;
2107
2108	/*
2109	 * Locate construction table for new channel list.  We treat
2110	 * the regdomain/SKU as definitive so a country can be in
2111	 * multiple with different properties (e.g. US in FCC+FCC3).
2112	 * If no regdomain is specified then we fallback on the country
2113	 * code to find the associated regdomain since countries always
2114	 * belong to at least one regdomain.
2115	 */
2116	if (reg->regdomain == 0) {
2117		cc = lib80211_country_findbycc(rdp, reg->country);
2118		if (cc == NULL)
2119			errx(1, "internal error, country %d not found",
2120			    reg->country);
2121		rd = cc->rd;
2122	} else
2123		rd = lib80211_regdomain_findbysku(rdp, reg->regdomain);
2124	if (rd == NULL)
2125		errx(1, "internal error, regdomain %d not found",
2126			    reg->regdomain);
2127	if (rd->sku != SKU_DEBUG) {
2128		/*
2129		 * regdomain_addchans incrememnts the channel count for
2130		 * each channel it adds so initialize ic_nchans to zero.
2131		 * Note that we know we have enough space to hold all possible
2132		 * channels because the devcaps list size was used to
2133		 * allocate our request.
2134		 */
2135		ci->ic_nchans = 0;
2136		if (!LIST_EMPTY(&rd->bands_11b))
2137			regdomain_addchans(ci, &rd->bands_11b, reg,
2138			    IEEE80211_CHAN_B, &dc->dc_chaninfo);
2139		if (!LIST_EMPTY(&rd->bands_11g))
2140			regdomain_addchans(ci, &rd->bands_11g, reg,
2141			    IEEE80211_CHAN_G, &dc->dc_chaninfo);
2142		if (!LIST_EMPTY(&rd->bands_11a))
2143			regdomain_addchans(ci, &rd->bands_11a, reg,
2144			    IEEE80211_CHAN_A, &dc->dc_chaninfo);
2145		if (!LIST_EMPTY(&rd->bands_11na) && dc->dc_htcaps != 0) {
2146			regdomain_addchans(ci, &rd->bands_11na, reg,
2147			    IEEE80211_CHAN_A | IEEE80211_CHAN_HT20,
2148			    &dc->dc_chaninfo);
2149			if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2150				regdomain_addchans(ci, &rd->bands_11na, reg,
2151				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U,
2152				    &dc->dc_chaninfo);
2153				regdomain_addchans(ci, &rd->bands_11na, reg,
2154				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D,
2155				    &dc->dc_chaninfo);
2156			}
2157		}
2158		if (!LIST_EMPTY(&rd->bands_11ng) && dc->dc_htcaps != 0) {
2159			regdomain_addchans(ci, &rd->bands_11ng, reg,
2160			    IEEE80211_CHAN_G | IEEE80211_CHAN_HT20,
2161			    &dc->dc_chaninfo);
2162			if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2163				regdomain_addchans(ci, &rd->bands_11ng, reg,
2164				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U,
2165				    &dc->dc_chaninfo);
2166				regdomain_addchans(ci, &rd->bands_11ng, reg,
2167				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D,
2168				    &dc->dc_chaninfo);
2169			}
2170		}
2171		qsort(ci->ic_chans, ci->ic_nchans, sizeof(ci->ic_chans[0]),
2172		    regdomain_sort);
2173	} else
2174		memcpy(ci, &dc->dc_chaninfo,
2175		    IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
2176}
2177
2178static void
2179list_countries(void)
2180{
2181	struct regdata *rdp = getregdata();
2182	const struct country *cp;
2183	const struct regdomain *dp;
2184	int i;
2185
2186	i = 0;
2187	printf("\nCountry codes:\n");
2188	LIST_FOREACH(cp, &rdp->countries, next) {
2189		printf("%2s %-15.15s%s", cp->isoname,
2190		    cp->name, ((i+1)%4) == 0 ? "\n" : " ");
2191		i++;
2192	}
2193	i = 0;
2194	printf("\nRegulatory domains:\n");
2195	LIST_FOREACH(dp, &rdp->domains, next) {
2196		printf("%-15.15s%s", dp->name, ((i+1)%4) == 0 ? "\n" : " ");
2197		i++;
2198	}
2199	printf("\n");
2200}
2201
2202static void
2203defaultcountry(const struct regdomain *rd)
2204{
2205	struct regdata *rdp = getregdata();
2206	const struct country *cc;
2207
2208	cc = lib80211_country_findbycc(rdp, rd->cc->code);
2209	if (cc == NULL)
2210		errx(1, "internal error, ISO country code %d not "
2211		    "defined for regdomain %s", rd->cc->code, rd->name);
2212	regdomain.country = cc->code;
2213	regdomain.isocc[0] = cc->isoname[0];
2214	regdomain.isocc[1] = cc->isoname[1];
2215}
2216
2217static
2218DECL_CMD_FUNC(set80211regdomain, val, d)
2219{
2220	struct regdata *rdp = getregdata();
2221	const struct regdomain *rd;
2222
2223	rd = lib80211_regdomain_findbyname(rdp, val);
2224	if (rd == NULL) {
2225		char *eptr;
2226		long sku = strtol(val, &eptr, 0);
2227
2228		if (eptr != val)
2229			rd = lib80211_regdomain_findbysku(rdp, sku);
2230		if (eptr == val || rd == NULL)
2231			errx(1, "unknown regdomain %s", val);
2232	}
2233	getregdomain(s);
2234	regdomain.regdomain = rd->sku;
2235	if (regdomain.country == 0 && rd->cc != NULL) {
2236		/*
2237		 * No country code setup and there's a default
2238		 * one for this regdomain fill it in.
2239		 */
2240		defaultcountry(rd);
2241	}
2242	callback_register(setregdomain_cb, &regdomain);
2243}
2244
2245static
2246DECL_CMD_FUNC(set80211country, val, d)
2247{
2248	struct regdata *rdp = getregdata();
2249	const struct country *cc;
2250
2251	cc = lib80211_country_findbyname(rdp, val);
2252	if (cc == NULL) {
2253		char *eptr;
2254		long code = strtol(val, &eptr, 0);
2255
2256		if (eptr != val)
2257			cc = lib80211_country_findbycc(rdp, code);
2258		if (eptr == val || cc == NULL)
2259			errx(1, "unknown ISO country code %s", val);
2260	}
2261	getregdomain(s);
2262	regdomain.regdomain = cc->rd->sku;
2263	regdomain.country = cc->code;
2264	regdomain.isocc[0] = cc->isoname[0];
2265	regdomain.isocc[1] = cc->isoname[1];
2266	callback_register(setregdomain_cb, &regdomain);
2267}
2268
2269static void
2270set80211location(const char *val, int d, int s, const struct afswtch *rafp)
2271{
2272	getregdomain(s);
2273	regdomain.location = d;
2274	callback_register(setregdomain_cb, &regdomain);
2275}
2276
2277static void
2278set80211ecm(const char *val, int d, int s, const struct afswtch *rafp)
2279{
2280	getregdomain(s);
2281	regdomain.ecm = d;
2282	callback_register(setregdomain_cb, &regdomain);
2283}
2284
2285static void
2286LINE_INIT(char c)
2287{
2288	spacer = c;
2289	if (c == '\t')
2290		col = 8;
2291	else
2292		col = 1;
2293}
2294
2295static void
2296LINE_BREAK(void)
2297{
2298	if (spacer != '\t') {
2299		printf("\n");
2300		spacer = '\t';
2301	}
2302	col = 8;		/* 8-col tab */
2303}
2304
2305static void
2306LINE_CHECK(const char *fmt, ...)
2307{
2308	char buf[80];
2309	va_list ap;
2310	int n;
2311
2312	va_start(ap, fmt);
2313	n = vsnprintf(buf+1, sizeof(buf)-1, fmt, ap);
2314	va_end(ap);
2315	col += 1+n;
2316	if (col > MAXCOL) {
2317		LINE_BREAK();
2318		col += n;
2319	}
2320	buf[0] = spacer;
2321	printf("%s", buf);
2322	spacer = ' ';
2323}
2324
2325static int
2326getmaxrate(const uint8_t rates[15], uint8_t nrates)
2327{
2328	int i, maxrate = -1;
2329
2330	for (i = 0; i < nrates; i++) {
2331		int rate = rates[i] & IEEE80211_RATE_VAL;
2332		if (rate > maxrate)
2333			maxrate = rate;
2334	}
2335	return maxrate / 2;
2336}
2337
2338static const char *
2339getcaps(int capinfo)
2340{
2341	static char capstring[32];
2342	char *cp = capstring;
2343
2344	if (capinfo & IEEE80211_CAPINFO_ESS)
2345		*cp++ = 'E';
2346	if (capinfo & IEEE80211_CAPINFO_IBSS)
2347		*cp++ = 'I';
2348	if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
2349		*cp++ = 'c';
2350	if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
2351		*cp++ = 'C';
2352	if (capinfo & IEEE80211_CAPINFO_PRIVACY)
2353		*cp++ = 'P';
2354	if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
2355		*cp++ = 'S';
2356	if (capinfo & IEEE80211_CAPINFO_PBCC)
2357		*cp++ = 'B';
2358	if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
2359		*cp++ = 'A';
2360	if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
2361		*cp++ = 's';
2362	if (capinfo & IEEE80211_CAPINFO_RSN)
2363		*cp++ = 'R';
2364	if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
2365		*cp++ = 'D';
2366	*cp = '\0';
2367	return capstring;
2368}
2369
2370static const char *
2371getflags(int flags)
2372{
2373	static char flagstring[32];
2374	char *cp = flagstring;
2375
2376	if (flags & IEEE80211_NODE_AUTH)
2377		*cp++ = 'A';
2378	if (flags & IEEE80211_NODE_QOS)
2379		*cp++ = 'Q';
2380	if (flags & IEEE80211_NODE_ERP)
2381		*cp++ = 'E';
2382	if (flags & IEEE80211_NODE_PWR_MGT)
2383		*cp++ = 'P';
2384	if (flags & IEEE80211_NODE_HT) {
2385		*cp++ = 'H';
2386		if (flags & IEEE80211_NODE_HTCOMPAT)
2387			*cp++ = '+';
2388	}
2389	if (flags & IEEE80211_NODE_WPS)
2390		*cp++ = 'W';
2391	if (flags & IEEE80211_NODE_TSN)
2392		*cp++ = 'N';
2393	if (flags & IEEE80211_NODE_AMPDU_TX)
2394		*cp++ = 'T';
2395	if (flags & IEEE80211_NODE_AMPDU_RX)
2396		*cp++ = 'R';
2397	if (flags & IEEE80211_NODE_MIMO_PS) {
2398		*cp++ = 'M';
2399		if (flags & IEEE80211_NODE_MIMO_RTS)
2400			*cp++ = '+';
2401	}
2402	if (flags & IEEE80211_NODE_RIFS)
2403		*cp++ = 'I';
2404	if (flags & IEEE80211_NODE_SGI40) {
2405		*cp++ = 'S';
2406		if (flags & IEEE80211_NODE_SGI20)
2407			*cp++ = '+';
2408	} else if (flags & IEEE80211_NODE_SGI20)
2409		*cp++ = 's';
2410	if (flags & IEEE80211_NODE_AMSDU_TX)
2411		*cp++ = 't';
2412	if (flags & IEEE80211_NODE_AMSDU_RX)
2413		*cp++ = 'r';
2414	*cp = '\0';
2415	return flagstring;
2416}
2417
2418static void
2419printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
2420{
2421	printf("%s", tag);
2422	if (verbose) {
2423		maxlen -= strlen(tag)+2;
2424		if (2*ielen > maxlen)
2425			maxlen--;
2426		printf("<");
2427		for (; ielen > 0; ie++, ielen--) {
2428			if (maxlen-- <= 0)
2429				break;
2430			printf("%02x", *ie);
2431		}
2432		if (ielen != 0)
2433			printf("-");
2434		printf(">");
2435	}
2436}
2437
2438#define LE_READ_2(p)					\
2439	((u_int16_t)					\
2440	 ((((const u_int8_t *)(p))[0]      ) |		\
2441	  (((const u_int8_t *)(p))[1] <<  8)))
2442#define LE_READ_4(p)					\
2443	((u_int32_t)					\
2444	 ((((const u_int8_t *)(p))[0]      ) |		\
2445	  (((const u_int8_t *)(p))[1] <<  8) |		\
2446	  (((const u_int8_t *)(p))[2] << 16) |		\
2447	  (((const u_int8_t *)(p))[3] << 24)))
2448
2449/*
2450 * NB: The decoding routines assume a properly formatted ie
2451 *     which should be safe as the kernel only retains them
2452 *     if they parse ok.
2453 */
2454
2455static void
2456printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2457{
2458#define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
2459	static const char *acnames[] = { "BE", "BK", "VO", "VI" };
2460	const struct ieee80211_wme_param *wme =
2461	    (const struct ieee80211_wme_param *) ie;
2462	int i;
2463
2464	printf("%s", tag);
2465	if (!verbose)
2466		return;
2467	printf("<qosinfo 0x%x", wme->param_qosInfo);
2468	ie += offsetof(struct ieee80211_wme_param, params_acParams);
2469	for (i = 0; i < WME_NUM_AC; i++) {
2470		const struct ieee80211_wme_acparams *ac =
2471		    &wme->params_acParams[i];
2472
2473		printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
2474			, acnames[i]
2475			, MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
2476			, MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
2477			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
2478			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
2479			, LE_READ_2(&ac->acp_txop)
2480		);
2481	}
2482	printf(">");
2483#undef MS
2484}
2485
2486static void
2487printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2488{
2489	printf("%s", tag);
2490	if (verbose) {
2491		const struct ieee80211_wme_info *wme =
2492		    (const struct ieee80211_wme_info *) ie;
2493		printf("<version 0x%x info 0x%x>",
2494		    wme->wme_version, wme->wme_info);
2495	}
2496}
2497
2498static void
2499printhtcap(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2500{
2501	printf("%s", tag);
2502	if (verbose) {
2503		const struct ieee80211_ie_htcap *htcap =
2504		    (const struct ieee80211_ie_htcap *) ie;
2505		const char *sep;
2506		int i, j;
2507
2508		printf("<cap 0x%x param 0x%x",
2509		    LE_READ_2(&htcap->hc_cap), htcap->hc_param);
2510		printf(" mcsset[");
2511		sep = "";
2512		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2513			if (isset(htcap->hc_mcsset, i)) {
2514				for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2515					if (isclr(htcap->hc_mcsset, j))
2516						break;
2517				j--;
2518				if (i == j)
2519					printf("%s%u", sep, i);
2520				else
2521					printf("%s%u-%u", sep, i, j);
2522				i += j-i;
2523				sep = ",";
2524			}
2525		printf("] extcap 0x%x txbf 0x%x antenna 0x%x>",
2526		    LE_READ_2(&htcap->hc_extcap),
2527		    LE_READ_4(&htcap->hc_txbf),
2528		    htcap->hc_antenna);
2529	}
2530}
2531
2532static void
2533printhtinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2534{
2535	printf("%s", tag);
2536	if (verbose) {
2537		const struct ieee80211_ie_htinfo *htinfo =
2538		    (const struct ieee80211_ie_htinfo *) ie;
2539		const char *sep;
2540		int i, j;
2541
2542		printf("<ctl %u, %x,%x,%x,%x", htinfo->hi_ctrlchannel,
2543		    htinfo->hi_byte1, htinfo->hi_byte2, htinfo->hi_byte3,
2544		    LE_READ_2(&htinfo->hi_byte45));
2545		printf(" basicmcs[");
2546		sep = "";
2547		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2548			if (isset(htinfo->hi_basicmcsset, i)) {
2549				for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2550					if (isclr(htinfo->hi_basicmcsset, j))
2551						break;
2552				j--;
2553				if (i == j)
2554					printf("%s%u", sep, i);
2555				else
2556					printf("%s%u-%u", sep, i, j);
2557				i += j-i;
2558				sep = ",";
2559			}
2560		printf("]>");
2561	}
2562}
2563
2564static void
2565printathie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2566{
2567
2568	printf("%s", tag);
2569	if (verbose) {
2570		const struct ieee80211_ath_ie *ath =
2571			(const struct ieee80211_ath_ie *)ie;
2572
2573		printf("<");
2574		if (ath->ath_capability & ATHEROS_CAP_TURBO_PRIME)
2575			printf("DTURBO,");
2576		if (ath->ath_capability & ATHEROS_CAP_COMPRESSION)
2577			printf("COMP,");
2578		if (ath->ath_capability & ATHEROS_CAP_FAST_FRAME)
2579			printf("FF,");
2580		if (ath->ath_capability & ATHEROS_CAP_XR)
2581			printf("XR,");
2582		if (ath->ath_capability & ATHEROS_CAP_AR)
2583			printf("AR,");
2584		if (ath->ath_capability & ATHEROS_CAP_BURST)
2585			printf("BURST,");
2586		if (ath->ath_capability & ATHEROS_CAP_WME)
2587			printf("WME,");
2588		if (ath->ath_capability & ATHEROS_CAP_BOOST)
2589			printf("BOOST,");
2590		printf("0x%x>", LE_READ_2(ath->ath_defkeyix));
2591	}
2592}
2593
2594
2595static void
2596printmeshconf(const char *tag, const uint8_t *ie, size_t ielen, int maxlen)
2597{
2598#define MATCHOUI(field, oui, string)					\
2599do {									\
2600	if (memcmp(field, oui, 4) == 0)					\
2601		printf("%s", string);					\
2602} while (0)
2603
2604	printf("%s", tag);
2605	if (verbose) {
2606		const struct ieee80211_meshconf_ie *mconf =
2607			(const struct ieee80211_meshconf_ie *)ie;
2608		printf("<PATH:");
2609		if (mconf->conf_pselid == IEEE80211_MESHCONF_PATH_HWMP)
2610			printf("HWMP");
2611		else
2612			printf("UNKNOWN");
2613		printf(" LINK:");
2614		if (mconf->conf_pmetid == IEEE80211_MESHCONF_METRIC_AIRTIME)
2615			printf("AIRTIME");
2616		else
2617			printf("UNKNOWN");
2618		printf(" CONGESTION:");
2619		if (mconf->conf_ccid == IEEE80211_MESHCONF_CC_DISABLED)
2620			printf("DISABLED");
2621		else
2622			printf("UNKNOWN");
2623		printf(" SYNC:");
2624		if (mconf->conf_syncid == IEEE80211_MESHCONF_SYNC_NEIGHOFF)
2625			printf("NEIGHOFF");
2626		else
2627			printf("UNKNOWN");
2628		printf(" AUTH:");
2629		if (mconf->conf_authid == IEEE80211_MESHCONF_AUTH_DISABLED)
2630			printf("DISABLED");
2631		else
2632			printf("UNKNOWN");
2633		printf(" FORM:0x%x CAPS:0x%x>", mconf->conf_form,
2634		    mconf->conf_cap);
2635	}
2636#undef MATCHOUI
2637}
2638
2639static const char *
2640wpa_cipher(const u_int8_t *sel)
2641{
2642#define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
2643	u_int32_t w = LE_READ_4(sel);
2644
2645	switch (w) {
2646	case WPA_SEL(WPA_CSE_NULL):
2647		return "NONE";
2648	case WPA_SEL(WPA_CSE_WEP40):
2649		return "WEP40";
2650	case WPA_SEL(WPA_CSE_WEP104):
2651		return "WEP104";
2652	case WPA_SEL(WPA_CSE_TKIP):
2653		return "TKIP";
2654	case WPA_SEL(WPA_CSE_CCMP):
2655		return "AES-CCMP";
2656	}
2657	return "?";		/* NB: so 1<< is discarded */
2658#undef WPA_SEL
2659}
2660
2661static const char *
2662wpa_keymgmt(const u_int8_t *sel)
2663{
2664#define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
2665	u_int32_t w = LE_READ_4(sel);
2666
2667	switch (w) {
2668	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
2669		return "8021X-UNSPEC";
2670	case WPA_SEL(WPA_ASE_8021X_PSK):
2671		return "8021X-PSK";
2672	case WPA_SEL(WPA_ASE_NONE):
2673		return "NONE";
2674	}
2675	return "?";
2676#undef WPA_SEL
2677}
2678
2679static void
2680printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2681{
2682	u_int8_t len = ie[1];
2683
2684	printf("%s", tag);
2685	if (verbose) {
2686		const char *sep;
2687		int n;
2688
2689		ie += 6, len -= 4;		/* NB: len is payload only */
2690
2691		printf("<v%u", LE_READ_2(ie));
2692		ie += 2, len -= 2;
2693
2694		printf(" mc:%s", wpa_cipher(ie));
2695		ie += 4, len -= 4;
2696
2697		/* unicast ciphers */
2698		n = LE_READ_2(ie);
2699		ie += 2, len -= 2;
2700		sep = " uc:";
2701		for (; n > 0; n--) {
2702			printf("%s%s", sep, wpa_cipher(ie));
2703			ie += 4, len -= 4;
2704			sep = "+";
2705		}
2706
2707		/* key management algorithms */
2708		n = LE_READ_2(ie);
2709		ie += 2, len -= 2;
2710		sep = " km:";
2711		for (; n > 0; n--) {
2712			printf("%s%s", sep, wpa_keymgmt(ie));
2713			ie += 4, len -= 4;
2714			sep = "+";
2715		}
2716
2717		if (len > 2)		/* optional capabilities */
2718			printf(", caps 0x%x", LE_READ_2(ie));
2719		printf(">");
2720	}
2721}
2722
2723static const char *
2724rsn_cipher(const u_int8_t *sel)
2725{
2726#define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
2727	u_int32_t w = LE_READ_4(sel);
2728
2729	switch (w) {
2730	case RSN_SEL(RSN_CSE_NULL):
2731		return "NONE";
2732	case RSN_SEL(RSN_CSE_WEP40):
2733		return "WEP40";
2734	case RSN_SEL(RSN_CSE_WEP104):
2735		return "WEP104";
2736	case RSN_SEL(RSN_CSE_TKIP):
2737		return "TKIP";
2738	case RSN_SEL(RSN_CSE_CCMP):
2739		return "AES-CCMP";
2740	case RSN_SEL(RSN_CSE_WRAP):
2741		return "AES-OCB";
2742	}
2743	return "?";
2744#undef WPA_SEL
2745}
2746
2747static const char *
2748rsn_keymgmt(const u_int8_t *sel)
2749{
2750#define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
2751	u_int32_t w = LE_READ_4(sel);
2752
2753	switch (w) {
2754	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
2755		return "8021X-UNSPEC";
2756	case RSN_SEL(RSN_ASE_8021X_PSK):
2757		return "8021X-PSK";
2758	case RSN_SEL(RSN_ASE_NONE):
2759		return "NONE";
2760	}
2761	return "?";
2762#undef RSN_SEL
2763}
2764
2765static void
2766printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2767{
2768	printf("%s", tag);
2769	if (verbose) {
2770		const char *sep;
2771		int n;
2772
2773		ie += 2, ielen -= 2;
2774
2775		printf("<v%u", LE_READ_2(ie));
2776		ie += 2, ielen -= 2;
2777
2778		printf(" mc:%s", rsn_cipher(ie));
2779		ie += 4, ielen -= 4;
2780
2781		/* unicast ciphers */
2782		n = LE_READ_2(ie);
2783		ie += 2, ielen -= 2;
2784		sep = " uc:";
2785		for (; n > 0; n--) {
2786			printf("%s%s", sep, rsn_cipher(ie));
2787			ie += 4, ielen -= 4;
2788			sep = "+";
2789		}
2790
2791		/* key management algorithms */
2792		n = LE_READ_2(ie);
2793		ie += 2, ielen -= 2;
2794		sep = " km:";
2795		for (; n > 0; n--) {
2796			printf("%s%s", sep, rsn_keymgmt(ie));
2797			ie += 4, ielen -= 4;
2798			sep = "+";
2799		}
2800
2801		if (ielen > 2)		/* optional capabilities */
2802			printf(", caps 0x%x", LE_READ_2(ie));
2803		/* XXXPMKID */
2804		printf(">");
2805	}
2806}
2807
2808/* XXX move to a public include file */
2809#define IEEE80211_WPS_DEV_PASS_ID	0x1012
2810#define IEEE80211_WPS_SELECTED_REG	0x1041
2811#define IEEE80211_WPS_SETUP_STATE	0x1044
2812#define IEEE80211_WPS_UUID_E		0x1047
2813#define IEEE80211_WPS_VERSION		0x104a
2814
2815#define BE_READ_2(p)					\
2816	((u_int16_t)					\
2817	 ((((const u_int8_t *)(p))[1]      ) |		\
2818	  (((const u_int8_t *)(p))[0] <<  8)))
2819
2820static void
2821printwpsie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2822{
2823#define	N(a)	(sizeof(a) / sizeof(a[0]))
2824	u_int8_t len = ie[1];
2825
2826	printf("%s", tag);
2827	if (verbose) {
2828		static const char *dev_pass_id[] = {
2829			"D",	/* Default (PIN) */
2830			"U",	/* User-specified */
2831			"M",	/* Machine-specified */
2832			"K",	/* Rekey */
2833			"P",	/* PushButton */
2834			"R"	/* Registrar-specified */
2835		};
2836		int n;
2837
2838		ie +=6, len -= 4;		/* NB: len is payload only */
2839
2840		/* WPS IE in Beacon and Probe Resp frames have different fields */
2841		printf("<");
2842		while (len) {
2843			uint16_t tlv_type = BE_READ_2(ie);
2844			uint16_t tlv_len  = BE_READ_2(ie + 2);
2845
2846			ie += 4, len -= 4;
2847
2848			switch (tlv_type) {
2849			case IEEE80211_WPS_VERSION:
2850				printf("v:%d.%d", *ie >> 4, *ie & 0xf);
2851				break;
2852			case IEEE80211_WPS_SETUP_STATE:
2853				/* Only 1 and 2 are valid */
2854				if (*ie == 0 || *ie >= 3)
2855					printf(" state:B");
2856				else
2857					printf(" st:%s", *ie == 1 ? "N" : "C");
2858				break;
2859			case IEEE80211_WPS_SELECTED_REG:
2860				printf(" sel:%s", *ie ? "T" : "F");
2861				break;
2862			case IEEE80211_WPS_DEV_PASS_ID:
2863				n = LE_READ_2(ie);
2864				if (n < N(dev_pass_id))
2865					printf(" dpi:%s", dev_pass_id[n]);
2866				break;
2867			case IEEE80211_WPS_UUID_E:
2868				printf(" uuid-e:");
2869				for (n = 0; n < (tlv_len - 1); n++)
2870					printf("%02x-", ie[n]);
2871				printf("%02x", ie[n]);
2872				break;
2873			}
2874			ie += tlv_len, len -= tlv_len;
2875		}
2876		printf(">");
2877	}
2878#undef N
2879}
2880
2881static void
2882printtdmaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2883{
2884	printf("%s", tag);
2885	if (verbose && ielen >= sizeof(struct ieee80211_tdma_param)) {
2886		const struct ieee80211_tdma_param *tdma =
2887		   (const struct ieee80211_tdma_param *) ie;
2888
2889		/* XXX tstamp */
2890		printf("<v%u slot:%u slotcnt:%u slotlen:%u bintval:%u inuse:0x%x>",
2891		    tdma->tdma_version, tdma->tdma_slot, tdma->tdma_slotcnt,
2892		    LE_READ_2(&tdma->tdma_slotlen), tdma->tdma_bintval,
2893		    tdma->tdma_inuse[0]);
2894	}
2895}
2896
2897/*
2898 * Copy the ssid string contents into buf, truncating to fit.  If the
2899 * ssid is entirely printable then just copy intact.  Otherwise convert
2900 * to hexadecimal.  If the result is truncated then replace the last
2901 * three characters with "...".
2902 */
2903static int
2904copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
2905{
2906	const u_int8_t *p;
2907	size_t maxlen;
2908	int i;
2909
2910	if (essid_len > bufsize)
2911		maxlen = bufsize;
2912	else
2913		maxlen = essid_len;
2914	/* determine printable or not */
2915	for (i = 0, p = essid; i < maxlen; i++, p++) {
2916		if (*p < ' ' || *p > 0x7e)
2917			break;
2918	}
2919	if (i != maxlen) {		/* not printable, print as hex */
2920		if (bufsize < 3)
2921			return 0;
2922		strlcpy(buf, "0x", bufsize);
2923		bufsize -= 2;
2924		p = essid;
2925		for (i = 0; i < maxlen && bufsize >= 2; i++) {
2926			sprintf(&buf[2+2*i], "%02x", p[i]);
2927			bufsize -= 2;
2928		}
2929		if (i != essid_len)
2930			memcpy(&buf[2+2*i-3], "...", 3);
2931	} else {			/* printable, truncate as needed */
2932		memcpy(buf, essid, maxlen);
2933		if (maxlen != essid_len)
2934			memcpy(&buf[maxlen-3], "...", 3);
2935	}
2936	return maxlen;
2937}
2938
2939static void
2940printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2941{
2942	char ssid[2*IEEE80211_NWID_LEN+1];
2943
2944	printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
2945}
2946
2947static void
2948printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2949{
2950	const char *sep;
2951	int i;
2952
2953	printf("%s", tag);
2954	sep = "<";
2955	for (i = 2; i < ielen; i++) {
2956		printf("%s%s%d", sep,
2957		    ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
2958		    ie[i] & IEEE80211_RATE_VAL);
2959		sep = ",";
2960	}
2961	printf(">");
2962}
2963
2964static void
2965printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2966{
2967	const struct ieee80211_country_ie *cie =
2968	   (const struct ieee80211_country_ie *) ie;
2969	int i, nbands, schan, nchan;
2970
2971	printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
2972	nbands = (cie->len - 3) / sizeof(cie->band[0]);
2973	for (i = 0; i < nbands; i++) {
2974		schan = cie->band[i].schan;
2975		nchan = cie->band[i].nchan;
2976		if (nchan != 1)
2977			printf(" %u-%u,%u", schan, schan + nchan-1,
2978			    cie->band[i].maxtxpwr);
2979		else
2980			printf(" %u,%u", schan, cie->band[i].maxtxpwr);
2981	}
2982	printf(">");
2983}
2984
2985/* unaligned little endian access */
2986#define LE_READ_4(p)					\
2987	((u_int32_t)					\
2988	 ((((const u_int8_t *)(p))[0]      ) |		\
2989	  (((const u_int8_t *)(p))[1] <<  8) |		\
2990	  (((const u_int8_t *)(p))[2] << 16) |		\
2991	  (((const u_int8_t *)(p))[3] << 24)))
2992
2993static __inline int
2994iswpaoui(const u_int8_t *frm)
2995{
2996	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
2997}
2998
2999static __inline int
3000iswmeinfo(const u_int8_t *frm)
3001{
3002	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
3003		frm[6] == WME_INFO_OUI_SUBTYPE;
3004}
3005
3006static __inline int
3007iswmeparam(const u_int8_t *frm)
3008{
3009	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
3010		frm[6] == WME_PARAM_OUI_SUBTYPE;
3011}
3012
3013static __inline int
3014isatherosoui(const u_int8_t *frm)
3015{
3016	return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
3017}
3018
3019static __inline int
3020istdmaoui(const uint8_t *frm)
3021{
3022	return frm[1] > 3 && LE_READ_4(frm+2) == ((TDMA_OUI_TYPE<<24)|TDMA_OUI);
3023}
3024
3025static __inline int
3026iswpsoui(const uint8_t *frm)
3027{
3028	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPS_OUI_TYPE<<24)|WPA_OUI);
3029}
3030
3031static const char *
3032iename(int elemid)
3033{
3034	switch (elemid) {
3035	case IEEE80211_ELEMID_FHPARMS:	return " FHPARMS";
3036	case IEEE80211_ELEMID_CFPARMS:	return " CFPARMS";
3037	case IEEE80211_ELEMID_TIM:	return " TIM";
3038	case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
3039	case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
3040	case IEEE80211_ELEMID_PWRCNSTR:	return " PWRCNSTR";
3041	case IEEE80211_ELEMID_PWRCAP:	return " PWRCAP";
3042	case IEEE80211_ELEMID_TPCREQ:	return " TPCREQ";
3043	case IEEE80211_ELEMID_TPCREP:	return " TPCREP";
3044	case IEEE80211_ELEMID_SUPPCHAN:	return " SUPPCHAN";
3045	case IEEE80211_ELEMID_CSA:	return " CSA";
3046	case IEEE80211_ELEMID_MEASREQ:	return " MEASREQ";
3047	case IEEE80211_ELEMID_MEASREP:	return " MEASREP";
3048	case IEEE80211_ELEMID_QUIET:	return " QUIET";
3049	case IEEE80211_ELEMID_IBSSDFS:	return " IBSSDFS";
3050	case IEEE80211_ELEMID_TPC:	return " TPC";
3051	case IEEE80211_ELEMID_CCKM:	return " CCKM";
3052	}
3053	return " ???";
3054}
3055
3056static void
3057printies(const u_int8_t *vp, int ielen, int maxcols)
3058{
3059	while (ielen > 0) {
3060		switch (vp[0]) {
3061		case IEEE80211_ELEMID_SSID:
3062			if (verbose)
3063				printssid(" SSID", vp, 2+vp[1], maxcols);
3064			break;
3065		case IEEE80211_ELEMID_RATES:
3066		case IEEE80211_ELEMID_XRATES:
3067			if (verbose)
3068				printrates(vp[0] == IEEE80211_ELEMID_RATES ?
3069				    " RATES" : " XRATES", vp, 2+vp[1], maxcols);
3070			break;
3071		case IEEE80211_ELEMID_DSPARMS:
3072			if (verbose)
3073				printf(" DSPARMS<%u>", vp[2]);
3074			break;
3075		case IEEE80211_ELEMID_COUNTRY:
3076			if (verbose)
3077				printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
3078			break;
3079		case IEEE80211_ELEMID_ERP:
3080			if (verbose)
3081				printf(" ERP<0x%x>", vp[2]);
3082			break;
3083		case IEEE80211_ELEMID_VENDOR:
3084			if (iswpaoui(vp))
3085				printwpaie(" WPA", vp, 2+vp[1], maxcols);
3086			else if (iswmeinfo(vp))
3087				printwmeinfo(" WME", vp, 2+vp[1], maxcols);
3088			else if (iswmeparam(vp))
3089				printwmeparam(" WME", vp, 2+vp[1], maxcols);
3090			else if (isatherosoui(vp))
3091				printathie(" ATH", vp, 2+vp[1], maxcols);
3092			else if (iswpsoui(vp))
3093				printwpsie(" WPS", vp, 2+vp[1], maxcols);
3094			else if (istdmaoui(vp))
3095				printtdmaie(" TDMA", vp, 2+vp[1], maxcols);
3096			else if (verbose)
3097				printie(" VEN", vp, 2+vp[1], maxcols);
3098			break;
3099		case IEEE80211_ELEMID_RSN:
3100			printrsnie(" RSN", vp, 2+vp[1], maxcols);
3101			break;
3102		case IEEE80211_ELEMID_HTCAP:
3103			printhtcap(" HTCAP", vp, 2+vp[1], maxcols);
3104			break;
3105		case IEEE80211_ELEMID_HTINFO:
3106			if (verbose)
3107				printhtinfo(" HTINFO", vp, 2+vp[1], maxcols);
3108			break;
3109		case IEEE80211_ELEMID_MESHID:
3110			if (verbose)
3111				printssid(" MESHID", vp, 2+vp[1], maxcols);
3112			break;
3113		case IEEE80211_ELEMID_MESHCONF:
3114			printmeshconf(" MESHCONF", vp, 2+vp[1], maxcols);
3115			break;
3116		default:
3117			if (verbose)
3118				printie(iename(vp[0]), vp, 2+vp[1], maxcols);
3119			break;
3120		}
3121		ielen -= 2+vp[1];
3122		vp += 2+vp[1];
3123	}
3124}
3125
3126static void
3127printmimo(const struct ieee80211_mimo_info *mi)
3128{
3129	/* NB: don't muddy display unless there's something to show */
3130	if (mi->rssi[0] != 0 || mi->rssi[1] != 0 || mi->rssi[2] != 0) {
3131		/* XXX ignore EVM for now */
3132		printf(" (rssi %d:%d:%d nf %d:%d:%d)",
3133		    mi->rssi[0], mi->rssi[1], mi->rssi[2],
3134		    mi->noise[0], mi->noise[1], mi->noise[2]);
3135	}
3136}
3137
3138static void
3139list_scan(int s)
3140{
3141	uint8_t buf[24*1024];
3142	char ssid[IEEE80211_NWID_LEN+1];
3143	const uint8_t *cp;
3144	int len, ssidmax, idlen;
3145
3146	if (get80211len(s, IEEE80211_IOC_SCAN_RESULTS, buf, sizeof(buf), &len) < 0)
3147		errx(1, "unable to get scan results");
3148	if (len < sizeof(struct ieee80211req_scan_result))
3149		return;
3150
3151	getchaninfo(s);
3152
3153	ssidmax = verbose ? IEEE80211_NWID_LEN - 1 : 14;
3154	printf("%-*.*s  %-17.17s  %4s %4s  %-7s  %3s %4s\n"
3155		, ssidmax, ssidmax, "SSID/MESH ID"
3156		, "BSSID"
3157		, "CHAN"
3158		, "RATE"
3159		, " S:N"
3160		, "INT"
3161		, "CAPS"
3162	);
3163	cp = buf;
3164	do {
3165		const struct ieee80211req_scan_result *sr;
3166		const uint8_t *vp, *idp;
3167
3168		sr = (const struct ieee80211req_scan_result *) cp;
3169		vp = cp + sr->isr_ie_off;
3170		if (sr->isr_meshid_len) {
3171			idp = vp + sr->isr_ssid_len;
3172			idlen = sr->isr_meshid_len;
3173		} else {
3174			idp = vp;
3175			idlen = sr->isr_ssid_len;
3176		}
3177		printf("%-*.*s  %s  %3d  %3dM %3d:%-3d  %3d %-4.4s"
3178			, ssidmax
3179			  , copy_essid(ssid, ssidmax, idp, idlen)
3180			  , ssid
3181			, ether_ntoa((const struct ether_addr *) sr->isr_bssid)
3182			, ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
3183			, getmaxrate(sr->isr_rates, sr->isr_nrates)
3184			, (sr->isr_rssi/2)+sr->isr_noise, sr->isr_noise
3185			, sr->isr_intval
3186			, getcaps(sr->isr_capinfo)
3187		);
3188		printies(vp + sr->isr_ssid_len + sr->isr_meshid_len,
3189		    sr->isr_ie_len, 24);
3190		printf("\n");
3191		cp += sr->isr_len, len -= sr->isr_len;
3192	} while (len >= sizeof(struct ieee80211req_scan_result));
3193}
3194
3195static void
3196scan_and_wait(int s)
3197{
3198	struct ieee80211_scan_req sr;
3199	struct ieee80211req ireq;
3200	int sroute;
3201
3202	sroute = socket(PF_ROUTE, SOCK_RAW, 0);
3203	if (sroute < 0) {
3204		perror("socket(PF_ROUTE,SOCK_RAW)");
3205		return;
3206	}
3207	(void) memset(&ireq, 0, sizeof(ireq));
3208	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3209	ireq.i_type = IEEE80211_IOC_SCAN_REQ;
3210
3211	memset(&sr, 0, sizeof(sr));
3212	sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE
3213		    | IEEE80211_IOC_SCAN_BGSCAN
3214		    | IEEE80211_IOC_SCAN_NOPICK
3215		    | IEEE80211_IOC_SCAN_ONCE;
3216	sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
3217	sr.sr_nssid = 0;
3218
3219	ireq.i_data = &sr;
3220	ireq.i_len = sizeof(sr);
3221	/*
3222	 * NB: only root can trigger a scan so ignore errors. Also ignore
3223	 * possible errors from net80211, even if no new scan could be
3224	 * started there might still be a valid scan cache.
3225	 */
3226	if (ioctl(s, SIOCS80211, &ireq) == 0) {
3227		char buf[2048];
3228		struct if_announcemsghdr *ifan;
3229		struct rt_msghdr *rtm;
3230
3231		do {
3232			if (read(sroute, buf, sizeof(buf)) < 0) {
3233				perror("read(PF_ROUTE)");
3234				break;
3235			}
3236			rtm = (struct rt_msghdr *) buf;
3237			if (rtm->rtm_version != RTM_VERSION)
3238				break;
3239			ifan = (struct if_announcemsghdr *) rtm;
3240		} while (rtm->rtm_type != RTM_IEEE80211 ||
3241		    ifan->ifan_what != RTM_IEEE80211_SCAN);
3242	}
3243	close(sroute);
3244}
3245
3246static
3247DECL_CMD_FUNC(set80211scan, val, d)
3248{
3249	scan_and_wait(s);
3250	list_scan(s);
3251}
3252
3253static enum ieee80211_opmode get80211opmode(int s);
3254
3255static int
3256gettxseq(const struct ieee80211req_sta_info *si)
3257{
3258	int i, txseq;
3259
3260	if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3261		return si->isi_txseqs[0];
3262	/* XXX not right but usually what folks want */
3263	txseq = 0;
3264	for (i = 0; i < IEEE80211_TID_SIZE; i++)
3265		if (si->isi_txseqs[i] > txseq)
3266			txseq = si->isi_txseqs[i];
3267	return txseq;
3268}
3269
3270static int
3271getrxseq(const struct ieee80211req_sta_info *si)
3272{
3273	int i, rxseq;
3274
3275	if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3276		return si->isi_rxseqs[0];
3277	/* XXX not right but usually what folks want */
3278	rxseq = 0;
3279	for (i = 0; i < IEEE80211_TID_SIZE; i++)
3280		if (si->isi_rxseqs[i] > rxseq)
3281			rxseq = si->isi_rxseqs[i];
3282	return rxseq;
3283}
3284
3285static void
3286list_stations(int s)
3287{
3288	union {
3289		struct ieee80211req_sta_req req;
3290		uint8_t buf[24*1024];
3291	} u;
3292	enum ieee80211_opmode opmode = get80211opmode(s);
3293	const uint8_t *cp;
3294	int len;
3295
3296	/* broadcast address =>'s get all stations */
3297	(void) memset(u.req.is_u.macaddr, 0xff, IEEE80211_ADDR_LEN);
3298	if (opmode == IEEE80211_M_STA) {
3299		/*
3300		 * Get information about the associated AP.
3301		 */
3302		(void) get80211(s, IEEE80211_IOC_BSSID,
3303		    u.req.is_u.macaddr, IEEE80211_ADDR_LEN);
3304	}
3305	if (get80211len(s, IEEE80211_IOC_STA_INFO, &u, sizeof(u), &len) < 0)
3306		errx(1, "unable to get station information");
3307	if (len < sizeof(struct ieee80211req_sta_info))
3308		return;
3309
3310	getchaninfo(s);
3311
3312	if (opmode == IEEE80211_M_MBSS)
3313		printf("%-17.17s %4s %5s %5s %7s %4s %4s %4s %6s %6s\n"
3314			, "ADDR"
3315			, "CHAN"
3316			, "LOCAL"
3317			, "PEER"
3318			, "STATE"
3319			, "RATE"
3320			, "RSSI"
3321			, "IDLE"
3322			, "TXSEQ"
3323			, "RXSEQ"
3324		);
3325	else
3326		printf("%-17.17s %4s %4s %4s %4s %4s %6s %6s %4s %-7s\n"
3327			, "ADDR"
3328			, "AID"
3329			, "CHAN"
3330			, "RATE"
3331			, "RSSI"
3332			, "IDLE"
3333			, "TXSEQ"
3334			, "RXSEQ"
3335			, "CAPS"
3336			, "FLAG"
3337		);
3338	cp = (const uint8_t *) u.req.info;
3339	do {
3340		const struct ieee80211req_sta_info *si;
3341
3342		si = (const struct ieee80211req_sta_info *) cp;
3343		if (si->isi_len < sizeof(*si))
3344			break;
3345		if (opmode == IEEE80211_M_MBSS)
3346			printf("%s %4d %5x %5x %7.7s %3dM %4.1f %4d %6d %6d"
3347				, ether_ntoa((const struct ether_addr*)
3348				    si->isi_macaddr)
3349				, ieee80211_mhz2ieee(si->isi_freq,
3350				    si->isi_flags)
3351				, si->isi_localid
3352				, si->isi_peerid
3353				, mesh_linkstate_string(si->isi_peerstate)
3354				, si->isi_txmbps/2
3355				, si->isi_rssi/2.
3356				, si->isi_inact
3357				, gettxseq(si)
3358				, getrxseq(si)
3359			);
3360		else
3361			printf("%s %4u %4d %3dM %4.1f %4d %6d %6d %-4.4s %-7.7s"
3362				, ether_ntoa((const struct ether_addr*)
3363				    si->isi_macaddr)
3364				, IEEE80211_AID(si->isi_associd)
3365				, ieee80211_mhz2ieee(si->isi_freq,
3366				    si->isi_flags)
3367				, si->isi_txmbps/2
3368				, si->isi_rssi/2.
3369				, si->isi_inact
3370				, gettxseq(si)
3371				, getrxseq(si)
3372				, getcaps(si->isi_capinfo)
3373				, getflags(si->isi_state)
3374			);
3375		printies(cp + si->isi_ie_off, si->isi_ie_len, 24);
3376		printmimo(&si->isi_mimo);
3377		printf("\n");
3378		cp += si->isi_len, len -= si->isi_len;
3379	} while (len >= sizeof(struct ieee80211req_sta_info));
3380}
3381
3382static const char *
3383mesh_linkstate_string(uint8_t state)
3384{
3385#define	N(a)	(sizeof(a) / sizeof(a[0]))
3386	static const char *state_names[] = {
3387	    [0] = "IDLE",
3388	    [1] = "OPEN-TX",
3389	    [2] = "OPEN-RX",
3390	    [3] = "CONF-RX",
3391	    [4] = "ESTAB",
3392	    [5] = "HOLDING",
3393	};
3394
3395	if (state >= N(state_names)) {
3396		static char buf[10];
3397		snprintf(buf, sizeof(buf), "#%u", state);
3398		return buf;
3399	} else
3400		return state_names[state];
3401#undef N
3402}
3403
3404static const char *
3405get_chaninfo(const struct ieee80211_channel *c, int precise,
3406	char buf[], size_t bsize)
3407{
3408	buf[0] = '\0';
3409	if (IEEE80211_IS_CHAN_FHSS(c))
3410		strlcat(buf, " FHSS", bsize);
3411	if (IEEE80211_IS_CHAN_A(c))
3412		strlcat(buf, " 11a", bsize);
3413	else if (IEEE80211_IS_CHAN_ANYG(c))
3414		strlcat(buf, " 11g", bsize);
3415	else if (IEEE80211_IS_CHAN_B(c))
3416		strlcat(buf, " 11b", bsize);
3417	if (IEEE80211_IS_CHAN_HALF(c))
3418		strlcat(buf, "/10MHz", bsize);
3419	if (IEEE80211_IS_CHAN_QUARTER(c))
3420		strlcat(buf, "/5MHz", bsize);
3421	if (IEEE80211_IS_CHAN_TURBO(c))
3422		strlcat(buf, " Turbo", bsize);
3423	if (precise) {
3424		if (IEEE80211_IS_CHAN_HT20(c))
3425			strlcat(buf, " ht/20", bsize);
3426		else if (IEEE80211_IS_CHAN_HT40D(c))
3427			strlcat(buf, " ht/40-", bsize);
3428		else if (IEEE80211_IS_CHAN_HT40U(c))
3429			strlcat(buf, " ht/40+", bsize);
3430	} else {
3431		if (IEEE80211_IS_CHAN_HT(c))
3432			strlcat(buf, " ht", bsize);
3433	}
3434	return buf;
3435}
3436
3437static void
3438print_chaninfo(const struct ieee80211_channel *c, int verb)
3439{
3440	char buf[14];
3441
3442	if (verb)
3443		printf("Channel %3u : %u%c%c%c%c%c MHz%-14.14s",
3444		    ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3445		    IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3446		    IEEE80211_IS_CHAN_DFS(c) ? 'D' : ' ',
3447		    IEEE80211_IS_CHAN_RADAR(c) ? 'R' : ' ',
3448		    IEEE80211_IS_CHAN_CWINT(c) ? 'I' : ' ',
3449		    IEEE80211_IS_CHAN_CACDONE(c) ? 'C' : ' ',
3450		    get_chaninfo(c, verb, buf, sizeof(buf)));
3451	else
3452	printf("Channel %3u : %u%c MHz%-14.14s",
3453	    ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3454	    IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3455	    get_chaninfo(c, verb, buf, sizeof(buf)));
3456
3457}
3458
3459static int
3460chanpref(const struct ieee80211_channel *c)
3461{
3462	if (IEEE80211_IS_CHAN_HT40(c))
3463		return 40;
3464	if (IEEE80211_IS_CHAN_HT20(c))
3465		return 30;
3466	if (IEEE80211_IS_CHAN_HALF(c))
3467		return 10;
3468	if (IEEE80211_IS_CHAN_QUARTER(c))
3469		return 5;
3470	if (IEEE80211_IS_CHAN_TURBO(c))
3471		return 25;
3472	if (IEEE80211_IS_CHAN_A(c))
3473		return 20;
3474	if (IEEE80211_IS_CHAN_G(c))
3475		return 20;
3476	if (IEEE80211_IS_CHAN_B(c))
3477		return 15;
3478	if (IEEE80211_IS_CHAN_PUREG(c))
3479		return 15;
3480	return 0;
3481}
3482
3483static void
3484print_channels(int s, const struct ieee80211req_chaninfo *chans,
3485	int allchans, int verb)
3486{
3487	struct ieee80211req_chaninfo *achans;
3488	uint8_t reported[IEEE80211_CHAN_BYTES];
3489	const struct ieee80211_channel *c;
3490	int i, half;
3491
3492	achans = malloc(IEEE80211_CHANINFO_SPACE(chans));
3493	if (achans == NULL)
3494		errx(1, "no space for active channel list");
3495	achans->ic_nchans = 0;
3496	memset(reported, 0, sizeof(reported));
3497	if (!allchans) {
3498		struct ieee80211req_chanlist active;
3499
3500		if (get80211(s, IEEE80211_IOC_CHANLIST, &active, sizeof(active)) < 0)
3501			errx(1, "unable to get active channel list");
3502		for (i = 0; i < chans->ic_nchans; i++) {
3503			c = &chans->ic_chans[i];
3504			if (!isset(active.ic_channels, c->ic_ieee))
3505				continue;
3506			/*
3507			 * Suppress compatible duplicates unless
3508			 * verbose.  The kernel gives us it's
3509			 * complete channel list which has separate
3510			 * entries for 11g/11b and 11a/turbo.
3511			 */
3512			if (isset(reported, c->ic_ieee) && !verb) {
3513				/* XXX we assume duplicates are adjacent */
3514				achans->ic_chans[achans->ic_nchans-1] = *c;
3515			} else {
3516				achans->ic_chans[achans->ic_nchans++] = *c;
3517				setbit(reported, c->ic_ieee);
3518			}
3519		}
3520	} else {
3521		for (i = 0; i < chans->ic_nchans; i++) {
3522			c = &chans->ic_chans[i];
3523			/* suppress duplicates as above */
3524			if (isset(reported, c->ic_ieee) && !verb) {
3525				/* XXX we assume duplicates are adjacent */
3526				struct ieee80211_channel *a =
3527				    &achans->ic_chans[achans->ic_nchans-1];
3528				if (chanpref(c) > chanpref(a))
3529					*a = *c;
3530			} else {
3531				achans->ic_chans[achans->ic_nchans++] = *c;
3532				setbit(reported, c->ic_ieee);
3533			}
3534		}
3535	}
3536	half = achans->ic_nchans / 2;
3537	if (achans->ic_nchans % 2)
3538		half++;
3539
3540	for (i = 0; i < achans->ic_nchans / 2; i++) {
3541		print_chaninfo(&achans->ic_chans[i], verb);
3542		print_chaninfo(&achans->ic_chans[half+i], verb);
3543		printf("\n");
3544	}
3545	if (achans->ic_nchans % 2) {
3546		print_chaninfo(&achans->ic_chans[i], verb);
3547		printf("\n");
3548	}
3549	free(achans);
3550}
3551
3552static void
3553list_channels(int s, int allchans)
3554{
3555	getchaninfo(s);
3556	print_channels(s, chaninfo, allchans, verbose);
3557}
3558
3559static void
3560print_txpow(const struct ieee80211_channel *c)
3561{
3562	printf("Channel %3u : %u MHz %3.1f reg %2d  ",
3563	    c->ic_ieee, c->ic_freq,
3564	    c->ic_maxpower/2., c->ic_maxregpower);
3565}
3566
3567static void
3568print_txpow_verbose(const struct ieee80211_channel *c)
3569{
3570	print_chaninfo(c, 1);
3571	printf("min %4.1f dBm  max %3.1f dBm  reg %2d dBm",
3572	    c->ic_minpower/2., c->ic_maxpower/2., c->ic_maxregpower);
3573	/* indicate where regulatory cap limits power use */
3574	if (c->ic_maxpower > 2*c->ic_maxregpower)
3575		printf(" <");
3576}
3577
3578static void
3579list_txpow(int s)
3580{
3581	struct ieee80211req_chaninfo *achans;
3582	uint8_t reported[IEEE80211_CHAN_BYTES];
3583	struct ieee80211_channel *c, *prev;
3584	int i, half;
3585
3586	getchaninfo(s);
3587	achans = malloc(IEEE80211_CHANINFO_SPACE(chaninfo));
3588	if (achans == NULL)
3589		errx(1, "no space for active channel list");
3590	achans->ic_nchans = 0;
3591	memset(reported, 0, sizeof(reported));
3592	for (i = 0; i < chaninfo->ic_nchans; i++) {
3593		c = &chaninfo->ic_chans[i];
3594		/* suppress duplicates as above */
3595		if (isset(reported, c->ic_ieee) && !verbose) {
3596			/* XXX we assume duplicates are adjacent */
3597			prev = &achans->ic_chans[achans->ic_nchans-1];
3598			/* display highest power on channel */
3599			if (c->ic_maxpower > prev->ic_maxpower)
3600				*prev = *c;
3601		} else {
3602			achans->ic_chans[achans->ic_nchans++] = *c;
3603			setbit(reported, c->ic_ieee);
3604		}
3605	}
3606	if (!verbose) {
3607		half = achans->ic_nchans / 2;
3608		if (achans->ic_nchans % 2)
3609			half++;
3610
3611		for (i = 0; i < achans->ic_nchans / 2; i++) {
3612			print_txpow(&achans->ic_chans[i]);
3613			print_txpow(&achans->ic_chans[half+i]);
3614			printf("\n");
3615		}
3616		if (achans->ic_nchans % 2) {
3617			print_txpow(&achans->ic_chans[i]);
3618			printf("\n");
3619		}
3620	} else {
3621		for (i = 0; i < achans->ic_nchans; i++) {
3622			print_txpow_verbose(&achans->ic_chans[i]);
3623			printf("\n");
3624		}
3625	}
3626	free(achans);
3627}
3628
3629static void
3630list_keys(int s)
3631{
3632}
3633
3634#define	IEEE80211_C_BITS \
3635	"\20\1STA\002803ENCAP\7FF\10TURBOP\11IBSS\12PMGT" \
3636	"\13HOSTAP\14AHDEMO\15SWRETRY\16TXPMGT\17SHSLOT\20SHPREAMBLE" \
3637	"\21MONITOR\22DFS\23MBSS\30WPA1\31WPA2\32BURST\33WME\34WDS\36BGSCAN" \
3638	"\37TXFRAG\40TDMA"
3639
3640static void
3641list_capabilities(int s)
3642{
3643	struct ieee80211_devcaps_req *dc;
3644
3645	if (verbose)
3646		dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
3647	else
3648		dc = malloc(IEEE80211_DEVCAPS_SIZE(1));
3649	if (dc == NULL)
3650		errx(1, "no space for device capabilities");
3651	dc->dc_chaninfo.ic_nchans = verbose ? MAXCHAN : 1;
3652	getdevcaps(s, dc);
3653	printb("drivercaps", dc->dc_drivercaps, IEEE80211_C_BITS);
3654	if (dc->dc_cryptocaps != 0 || verbose) {
3655		putchar('\n');
3656		printb("cryptocaps", dc->dc_cryptocaps, IEEE80211_CRYPTO_BITS);
3657	}
3658	if (dc->dc_htcaps != 0 || verbose) {
3659		putchar('\n');
3660		printb("htcaps", dc->dc_htcaps, IEEE80211_HTCAP_BITS);
3661	}
3662	putchar('\n');
3663	if (verbose) {
3664		chaninfo = &dc->dc_chaninfo;	/* XXX */
3665		print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, verbose);
3666	}
3667	free(dc);
3668}
3669
3670static int
3671get80211wme(int s, int param, int ac, int *val)
3672{
3673	struct ieee80211req ireq;
3674
3675	(void) memset(&ireq, 0, sizeof(ireq));
3676	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3677	ireq.i_type = param;
3678	ireq.i_len = ac;
3679	if (ioctl(s, SIOCG80211, &ireq) < 0) {
3680		warn("cannot get WME parameter %d, ac %d%s",
3681		    param, ac & IEEE80211_WMEPARAM_VAL,
3682		    ac & IEEE80211_WMEPARAM_BSS ? " (BSS)" : "");
3683		return -1;
3684	}
3685	*val = ireq.i_val;
3686	return 0;
3687}
3688
3689static void
3690list_wme_aci(int s, const char *tag, int ac)
3691{
3692	int val;
3693
3694	printf("\t%s", tag);
3695
3696	/* show WME BSS parameters */
3697	if (get80211wme(s, IEEE80211_IOC_WME_CWMIN, ac, &val) != -1)
3698		printf(" cwmin %2u", val);
3699	if (get80211wme(s, IEEE80211_IOC_WME_CWMAX, ac, &val) != -1)
3700		printf(" cwmax %2u", val);
3701	if (get80211wme(s, IEEE80211_IOC_WME_AIFS, ac, &val) != -1)
3702		printf(" aifs %2u", val);
3703	if (get80211wme(s, IEEE80211_IOC_WME_TXOPLIMIT, ac, &val) != -1)
3704		printf(" txopLimit %3u", val);
3705	if (get80211wme(s, IEEE80211_IOC_WME_ACM, ac, &val) != -1) {
3706		if (val)
3707			printf(" acm");
3708		else if (verbose)
3709			printf(" -acm");
3710	}
3711	/* !BSS only */
3712	if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
3713		if (get80211wme(s, IEEE80211_IOC_WME_ACKPOLICY, ac, &val) != -1) {
3714			if (!val)
3715				printf(" -ack");
3716			else if (verbose)
3717				printf(" ack");
3718		}
3719	}
3720	printf("\n");
3721}
3722
3723static void
3724list_wme(int s)
3725{
3726	static const char *acnames[] = { "AC_BE", "AC_BK", "AC_VI", "AC_VO" };
3727	int ac;
3728
3729	if (verbose) {
3730		/* display both BSS and local settings */
3731		for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++) {
3732	again:
3733			if (ac & IEEE80211_WMEPARAM_BSS)
3734				list_wme_aci(s, "     ", ac);
3735			else
3736				list_wme_aci(s, acnames[ac], ac);
3737			if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
3738				ac |= IEEE80211_WMEPARAM_BSS;
3739				goto again;
3740			} else
3741				ac &= ~IEEE80211_WMEPARAM_BSS;
3742		}
3743	} else {
3744		/* display only channel settings */
3745		for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++)
3746			list_wme_aci(s, acnames[ac], ac);
3747	}
3748}
3749
3750static void
3751list_roam(int s)
3752{
3753	const struct ieee80211_roamparam *rp;
3754	int mode;
3755
3756	getroam(s);
3757	for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
3758		rp = &roamparams.params[mode];
3759		if (rp->rssi == 0 && rp->rate == 0)
3760			continue;
3761		if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
3762			if (rp->rssi & 1)
3763				LINE_CHECK("roam:%-7.7s rssi %2u.5dBm  MCS %2u    ",
3764				    modename[mode], rp->rssi/2,
3765				    rp->rate &~ IEEE80211_RATE_MCS);
3766			else
3767				LINE_CHECK("roam:%-7.7s rssi %4udBm  MCS %2u    ",
3768				    modename[mode], rp->rssi/2,
3769				    rp->rate &~ IEEE80211_RATE_MCS);
3770		} else {
3771			if (rp->rssi & 1)
3772				LINE_CHECK("roam:%-7.7s rssi %2u.5dBm rate %2u Mb/s",
3773				    modename[mode], rp->rssi/2, rp->rate/2);
3774			else
3775				LINE_CHECK("roam:%-7.7s rssi %4udBm rate %2u Mb/s",
3776				    modename[mode], rp->rssi/2, rp->rate/2);
3777		}
3778	}
3779}
3780
3781static void
3782list_txparams(int s)
3783{
3784	const struct ieee80211_txparam *tp;
3785	int mode;
3786
3787	gettxparams(s);
3788	for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
3789		tp = &txparams.params[mode];
3790		if (tp->mgmtrate == 0 && tp->mcastrate == 0)
3791			continue;
3792		if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
3793			if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
3794				LINE_CHECK("%-7.7s ucast NONE    mgmt %2u MCS  "
3795				    "mcast %2u MCS  maxretry %u",
3796				    modename[mode],
3797				    tp->mgmtrate &~ IEEE80211_RATE_MCS,
3798				    tp->mcastrate &~ IEEE80211_RATE_MCS,
3799				    tp->maxretry);
3800			else
3801				LINE_CHECK("%-7.7s ucast %2u MCS  mgmt %2u MCS  "
3802				    "mcast %2u MCS  maxretry %u",
3803				    modename[mode],
3804				    tp->ucastrate &~ IEEE80211_RATE_MCS,
3805				    tp->mgmtrate &~ IEEE80211_RATE_MCS,
3806				    tp->mcastrate &~ IEEE80211_RATE_MCS,
3807				    tp->maxretry);
3808		} else {
3809			if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
3810				LINE_CHECK("%-7.7s ucast NONE    mgmt %2u Mb/s "
3811				    "mcast %2u Mb/s maxretry %u",
3812				    modename[mode],
3813				    tp->mgmtrate/2,
3814				    tp->mcastrate/2, tp->maxretry);
3815			else
3816				LINE_CHECK("%-7.7s ucast %2u Mb/s mgmt %2u Mb/s "
3817				    "mcast %2u Mb/s maxretry %u",
3818				    modename[mode],
3819				    tp->ucastrate/2, tp->mgmtrate/2,
3820				    tp->mcastrate/2, tp->maxretry);
3821		}
3822	}
3823}
3824
3825static void
3826printpolicy(int policy)
3827{
3828	switch (policy) {
3829	case IEEE80211_MACCMD_POLICY_OPEN:
3830		printf("policy: open\n");
3831		break;
3832	case IEEE80211_MACCMD_POLICY_ALLOW:
3833		printf("policy: allow\n");
3834		break;
3835	case IEEE80211_MACCMD_POLICY_DENY:
3836		printf("policy: deny\n");
3837		break;
3838	case IEEE80211_MACCMD_POLICY_RADIUS:
3839		printf("policy: radius\n");
3840		break;
3841	default:
3842		printf("policy: unknown (%u)\n", policy);
3843		break;
3844	}
3845}
3846
3847static void
3848list_mac(int s)
3849{
3850	struct ieee80211req ireq;
3851	struct ieee80211req_maclist *acllist;
3852	int i, nacls, policy, len;
3853	uint8_t *data;
3854	char c;
3855
3856	(void) memset(&ireq, 0, sizeof(ireq));
3857	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name)); /* XXX ?? */
3858	ireq.i_type = IEEE80211_IOC_MACCMD;
3859	ireq.i_val = IEEE80211_MACCMD_POLICY;
3860	if (ioctl(s, SIOCG80211, &ireq) < 0) {
3861		if (errno == EINVAL) {
3862			printf("No acl policy loaded\n");
3863			return;
3864		}
3865		err(1, "unable to get mac policy");
3866	}
3867	policy = ireq.i_val;
3868	if (policy == IEEE80211_MACCMD_POLICY_OPEN) {
3869		c = '*';
3870	} else if (policy == IEEE80211_MACCMD_POLICY_ALLOW) {
3871		c = '+';
3872	} else if (policy == IEEE80211_MACCMD_POLICY_DENY) {
3873		c = '-';
3874	} else if (policy == IEEE80211_MACCMD_POLICY_RADIUS) {
3875		c = 'r';		/* NB: should never have entries */
3876	} else {
3877		printf("policy: unknown (%u)\n", policy);
3878		c = '?';
3879	}
3880	if (verbose || c == '?')
3881		printpolicy(policy);
3882
3883	ireq.i_val = IEEE80211_MACCMD_LIST;
3884	ireq.i_len = 0;
3885	if (ioctl(s, SIOCG80211, &ireq) < 0)
3886		err(1, "unable to get mac acl list size");
3887	if (ireq.i_len == 0) {		/* NB: no acls */
3888		if (!(verbose || c == '?'))
3889			printpolicy(policy);
3890		return;
3891	}
3892	len = ireq.i_len;
3893
3894	data = malloc(len);
3895	if (data == NULL)
3896		err(1, "out of memory for acl list");
3897
3898	ireq.i_data = data;
3899	if (ioctl(s, SIOCG80211, &ireq) < 0)
3900		err(1, "unable to get mac acl list");
3901	nacls = len / sizeof(*acllist);
3902	acllist = (struct ieee80211req_maclist *) data;
3903	for (i = 0; i < nacls; i++)
3904		printf("%c%s\n", c, ether_ntoa(
3905			(const struct ether_addr *) acllist[i].ml_macaddr));
3906	free(data);
3907}
3908
3909static void
3910print_regdomain(const struct ieee80211_regdomain *reg, int verb)
3911{
3912	if ((reg->regdomain != 0 &&
3913	    reg->regdomain != reg->country) || verb) {
3914		const struct regdomain *rd =
3915		    lib80211_regdomain_findbysku(getregdata(), reg->regdomain);
3916		if (rd == NULL)
3917			LINE_CHECK("regdomain %d", reg->regdomain);
3918		else
3919			LINE_CHECK("regdomain %s", rd->name);
3920	}
3921	if (reg->country != 0 || verb) {
3922		const struct country *cc =
3923		    lib80211_country_findbycc(getregdata(), reg->country);
3924		if (cc == NULL)
3925			LINE_CHECK("country %d", reg->country);
3926		else
3927			LINE_CHECK("country %s", cc->isoname);
3928	}
3929	if (reg->location == 'I')
3930		LINE_CHECK("indoor");
3931	else if (reg->location == 'O')
3932		LINE_CHECK("outdoor");
3933	else if (verb)
3934		LINE_CHECK("anywhere");
3935	if (reg->ecm)
3936		LINE_CHECK("ecm");
3937	else if (verb)
3938		LINE_CHECK("-ecm");
3939}
3940
3941static void
3942list_regdomain(int s, int channelsalso)
3943{
3944	getregdomain(s);
3945	if (channelsalso) {
3946		getchaninfo(s);
3947		spacer = ':';
3948		print_regdomain(&regdomain, 1);
3949		LINE_BREAK();
3950		print_channels(s, chaninfo, 1/*allchans*/, 1/*verbose*/);
3951	} else
3952		print_regdomain(&regdomain, verbose);
3953}
3954
3955static void
3956list_mesh(int s)
3957{
3958	struct ieee80211req ireq;
3959	struct ieee80211req_mesh_route routes[128];
3960	struct ieee80211req_mesh_route *rt;
3961
3962	(void) memset(&ireq, 0, sizeof(ireq));
3963	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3964	ireq.i_type = IEEE80211_IOC_MESH_RTCMD;
3965	ireq.i_val = IEEE80211_MESH_RTCMD_LIST;
3966	ireq.i_data = &routes;
3967	ireq.i_len = sizeof(routes);
3968	if (ioctl(s, SIOCG80211, &ireq) < 0)
3969	 	err(1, "unable to get the Mesh routing table");
3970
3971	printf("%-17.17s %-17.17s %4s %4s %4s %6s %s\n"
3972		, "DEST"
3973		, "NEXT HOP"
3974		, "HOPS"
3975		, "METRIC"
3976		, "LIFETIME"
3977		, "MSEQ"
3978		, "FLAGS");
3979
3980	for (rt = &routes[0]; rt - &routes[0] < ireq.i_len / sizeof(*rt); rt++){
3981		printf("%s ",
3982		    ether_ntoa((const struct ether_addr *)rt->imr_dest));
3983		printf("%s %4u   %4u   %6u %6u    %c%c\n",
3984			ether_ntoa((const struct ether_addr *)rt->imr_nexthop),
3985			rt->imr_nhops, rt->imr_metric, rt->imr_lifetime,
3986			rt->imr_lastmseq,
3987			(rt->imr_flags & IEEE80211_MESHRT_FLAGS_VALID) ?
3988			    'V' : '!',
3989			(rt->imr_flags & IEEE80211_MESHRT_FLAGS_PROXY) ?
3990			    'P' : ' ');
3991	}
3992}
3993
3994static
3995DECL_CMD_FUNC(set80211list, arg, d)
3996{
3997#define	iseq(a,b)	(strncasecmp(a,b,sizeof(b)-1) == 0)
3998
3999	LINE_INIT('\t');
4000
4001	if (iseq(arg, "sta"))
4002		list_stations(s);
4003	else if (iseq(arg, "scan") || iseq(arg, "ap"))
4004		list_scan(s);
4005	else if (iseq(arg, "chan") || iseq(arg, "freq"))
4006		list_channels(s, 1);
4007	else if (iseq(arg, "active"))
4008		list_channels(s, 0);
4009	else if (iseq(arg, "keys"))
4010		list_keys(s);
4011	else if (iseq(arg, "caps"))
4012		list_capabilities(s);
4013	else if (iseq(arg, "wme") || iseq(arg, "wmm"))
4014		list_wme(s);
4015	else if (iseq(arg, "mac"))
4016		list_mac(s);
4017	else if (iseq(arg, "txpow"))
4018		list_txpow(s);
4019	else if (iseq(arg, "roam"))
4020		list_roam(s);
4021	else if (iseq(arg, "txparam") || iseq(arg, "txparm"))
4022		list_txparams(s);
4023	else if (iseq(arg, "regdomain"))
4024		list_regdomain(s, 1);
4025	else if (iseq(arg, "countries"))
4026		list_countries();
4027	else if (iseq(arg, "mesh"))
4028		list_mesh(s);
4029	else
4030		errx(1, "Don't know how to list %s for %s", arg, name);
4031	LINE_BREAK();
4032#undef iseq
4033}
4034
4035static enum ieee80211_opmode
4036get80211opmode(int s)
4037{
4038	struct ifmediareq ifmr;
4039
4040	(void) memset(&ifmr, 0, sizeof(ifmr));
4041	(void) strncpy(ifmr.ifm_name, name, sizeof(ifmr.ifm_name));
4042
4043	if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0) {
4044		if (ifmr.ifm_current & IFM_IEEE80211_ADHOC) {
4045			if (ifmr.ifm_current & IFM_FLAG0)
4046				return IEEE80211_M_AHDEMO;
4047			else
4048				return IEEE80211_M_IBSS;
4049		}
4050		if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
4051			return IEEE80211_M_HOSTAP;
4052		if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
4053			return IEEE80211_M_MONITOR;
4054		if (ifmr.ifm_current & IFM_IEEE80211_MBSS)
4055			return IEEE80211_M_MBSS;
4056	}
4057	return IEEE80211_M_STA;
4058}
4059
4060#if 0
4061static void
4062printcipher(int s, struct ieee80211req *ireq, int keylenop)
4063{
4064	switch (ireq->i_val) {
4065	case IEEE80211_CIPHER_WEP:
4066		ireq->i_type = keylenop;
4067		if (ioctl(s, SIOCG80211, ireq) != -1)
4068			printf("WEP-%s",
4069			    ireq->i_len <= 5 ? "40" :
4070			    ireq->i_len <= 13 ? "104" : "128");
4071		else
4072			printf("WEP");
4073		break;
4074	case IEEE80211_CIPHER_TKIP:
4075		printf("TKIP");
4076		break;
4077	case IEEE80211_CIPHER_AES_OCB:
4078		printf("AES-OCB");
4079		break;
4080	case IEEE80211_CIPHER_AES_CCM:
4081		printf("AES-CCM");
4082		break;
4083	case IEEE80211_CIPHER_CKIP:
4084		printf("CKIP");
4085		break;
4086	case IEEE80211_CIPHER_NONE:
4087		printf("NONE");
4088		break;
4089	default:
4090		printf("UNKNOWN (0x%x)", ireq->i_val);
4091		break;
4092	}
4093}
4094#endif
4095
4096static void
4097printkey(const struct ieee80211req_key *ik)
4098{
4099	static const uint8_t zerodata[IEEE80211_KEYBUF_SIZE];
4100	int keylen = ik->ik_keylen;
4101	int printcontents;
4102
4103	printcontents = printkeys &&
4104		(memcmp(ik->ik_keydata, zerodata, keylen) != 0 || verbose);
4105	if (printcontents)
4106		LINE_BREAK();
4107	switch (ik->ik_type) {
4108	case IEEE80211_CIPHER_WEP:
4109		/* compatibility */
4110		LINE_CHECK("wepkey %u:%s", ik->ik_keyix+1,
4111		    keylen <= 5 ? "40-bit" :
4112		    keylen <= 13 ? "104-bit" : "128-bit");
4113		break;
4114	case IEEE80211_CIPHER_TKIP:
4115		if (keylen > 128/8)
4116			keylen -= 128/8;	/* ignore MIC for now */
4117		LINE_CHECK("TKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4118		break;
4119	case IEEE80211_CIPHER_AES_OCB:
4120		LINE_CHECK("AES-OCB %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4121		break;
4122	case IEEE80211_CIPHER_AES_CCM:
4123		LINE_CHECK("AES-CCM %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4124		break;
4125	case IEEE80211_CIPHER_CKIP:
4126		LINE_CHECK("CKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4127		break;
4128	case IEEE80211_CIPHER_NONE:
4129		LINE_CHECK("NULL %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4130		break;
4131	default:
4132		LINE_CHECK("UNKNOWN (0x%x) %u:%u-bit",
4133			ik->ik_type, ik->ik_keyix+1, 8*keylen);
4134		break;
4135	}
4136	if (printcontents) {
4137		int i;
4138
4139		printf(" <");
4140		for (i = 0; i < keylen; i++)
4141			printf("%02x", ik->ik_keydata[i]);
4142		printf(">");
4143		if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4144		    (ik->ik_keyrsc != 0 || verbose))
4145			printf(" rsc %ju", (uintmax_t)ik->ik_keyrsc);
4146		if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4147		    (ik->ik_keytsc != 0 || verbose))
4148			printf(" tsc %ju", (uintmax_t)ik->ik_keytsc);
4149		if (ik->ik_flags != 0 && verbose) {
4150			const char *sep = " ";
4151
4152			if (ik->ik_flags & IEEE80211_KEY_XMIT)
4153				printf("%stx", sep), sep = "+";
4154			if (ik->ik_flags & IEEE80211_KEY_RECV)
4155				printf("%srx", sep), sep = "+";
4156			if (ik->ik_flags & IEEE80211_KEY_DEFAULT)
4157				printf("%sdef", sep), sep = "+";
4158		}
4159		LINE_BREAK();
4160	}
4161}
4162
4163static void
4164printrate(const char *tag, int v, int defrate, int defmcs)
4165{
4166	if ((v & IEEE80211_RATE_MCS) == 0) {
4167		if (v != defrate) {
4168			if (v & 1)
4169				LINE_CHECK("%s %d.5", tag, v/2);
4170			else
4171				LINE_CHECK("%s %d", tag, v/2);
4172		}
4173	} else {
4174		if (v != defmcs)
4175			LINE_CHECK("%s %d", tag, v &~ 0x80);
4176	}
4177}
4178
4179static int
4180getid(int s, int ix, void *data, size_t len, int *plen, int mesh)
4181{
4182	struct ieee80211req ireq;
4183
4184	(void) memset(&ireq, 0, sizeof(ireq));
4185	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4186	ireq.i_type = (!mesh) ? IEEE80211_IOC_SSID : IEEE80211_IOC_MESH_ID;
4187	ireq.i_val = ix;
4188	ireq.i_data = data;
4189	ireq.i_len = len;
4190	if (ioctl(s, SIOCG80211, &ireq) < 0)
4191		return -1;
4192	*plen = ireq.i_len;
4193	return 0;
4194}
4195
4196static void
4197ieee80211_status(int s)
4198{
4199	static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
4200	enum ieee80211_opmode opmode = get80211opmode(s);
4201	int i, num, wpa, wme, bgscan, bgscaninterval, val, len, wepmode;
4202	uint8_t data[32];
4203	const struct ieee80211_channel *c;
4204	const struct ieee80211_roamparam *rp;
4205	const struct ieee80211_txparam *tp;
4206
4207	if (getid(s, -1, data, sizeof(data), &len, 0) < 0) {
4208		/* If we can't get the SSID, this isn't an 802.11 device. */
4209		return;
4210	}
4211
4212	/*
4213	 * Invalidate cached state so printing status for multiple
4214	 * if's doesn't reuse the first interfaces' cached state.
4215	 */
4216	gotcurchan = 0;
4217	gotroam = 0;
4218	gottxparams = 0;
4219	gothtconf = 0;
4220	gotregdomain = 0;
4221
4222	printf("\t");
4223	if (opmode == IEEE80211_M_MBSS) {
4224		printf("meshid ");
4225		getid(s, 0, data, sizeof(data), &len, 1);
4226		print_string(data, len);
4227	} else {
4228		if (get80211val(s, IEEE80211_IOC_NUMSSIDS, &num) < 0)
4229			num = 0;
4230		printf("ssid ");
4231		if (num > 1) {
4232			for (i = 0; i < num; i++) {
4233				if (getid(s, i, data, sizeof(data), &len, 0) >= 0 && len > 0) {
4234					printf(" %d:", i + 1);
4235					print_string(data, len);
4236				}
4237			}
4238		} else
4239			print_string(data, len);
4240	}
4241	c = getcurchan(s);
4242	if (c->ic_freq != IEEE80211_CHAN_ANY) {
4243		char buf[14];
4244		printf(" channel %d (%u MHz%s)", c->ic_ieee, c->ic_freq,
4245			get_chaninfo(c, 1, buf, sizeof(buf)));
4246	} else if (verbose)
4247		printf(" channel UNDEF");
4248
4249	if (get80211(s, IEEE80211_IOC_BSSID, data, IEEE80211_ADDR_LEN) >= 0 &&
4250	    (memcmp(data, zerobssid, sizeof(zerobssid)) != 0 || verbose))
4251		printf(" bssid %s", ether_ntoa((struct ether_addr *)data));
4252
4253	if (get80211len(s, IEEE80211_IOC_STATIONNAME, data, sizeof(data), &len) != -1) {
4254		printf("\n\tstationname ");
4255		print_string(data, len);
4256	}
4257
4258	spacer = ' ';		/* force first break */
4259	LINE_BREAK();
4260
4261	list_regdomain(s, 0);
4262
4263	wpa = 0;
4264	if (get80211val(s, IEEE80211_IOC_AUTHMODE, &val) != -1) {
4265		switch (val) {
4266		case IEEE80211_AUTH_NONE:
4267			LINE_CHECK("authmode NONE");
4268			break;
4269		case IEEE80211_AUTH_OPEN:
4270			LINE_CHECK("authmode OPEN");
4271			break;
4272		case IEEE80211_AUTH_SHARED:
4273			LINE_CHECK("authmode SHARED");
4274			break;
4275		case IEEE80211_AUTH_8021X:
4276			LINE_CHECK("authmode 802.1x");
4277			break;
4278		case IEEE80211_AUTH_WPA:
4279			if (get80211val(s, IEEE80211_IOC_WPA, &wpa) < 0)
4280				wpa = 1;	/* default to WPA1 */
4281			switch (wpa) {
4282			case 2:
4283				LINE_CHECK("authmode WPA2/802.11i");
4284				break;
4285			case 3:
4286				LINE_CHECK("authmode WPA1+WPA2/802.11i");
4287				break;
4288			default:
4289				LINE_CHECK("authmode WPA");
4290				break;
4291			}
4292			break;
4293		case IEEE80211_AUTH_AUTO:
4294			LINE_CHECK("authmode AUTO");
4295			break;
4296		default:
4297			LINE_CHECK("authmode UNKNOWN (0x%x)", val);
4298			break;
4299		}
4300	}
4301
4302	if (wpa || verbose) {
4303		if (get80211val(s, IEEE80211_IOC_WPS, &val) != -1) {
4304			if (val)
4305				LINE_CHECK("wps");
4306			else if (verbose)
4307				LINE_CHECK("-wps");
4308		}
4309		if (get80211val(s, IEEE80211_IOC_TSN, &val) != -1) {
4310			if (val)
4311				LINE_CHECK("tsn");
4312			else if (verbose)
4313				LINE_CHECK("-tsn");
4314		}
4315		if (ioctl(s, IEEE80211_IOC_COUNTERMEASURES, &val) != -1) {
4316			if (val)
4317				LINE_CHECK("countermeasures");
4318			else if (verbose)
4319				LINE_CHECK("-countermeasures");
4320		}
4321#if 0
4322		/* XXX not interesting with WPA done in user space */
4323		ireq.i_type = IEEE80211_IOC_KEYMGTALGS;
4324		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4325		}
4326
4327		ireq.i_type = IEEE80211_IOC_MCASTCIPHER;
4328		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4329			LINE_CHECK("mcastcipher ");
4330			printcipher(s, &ireq, IEEE80211_IOC_MCASTKEYLEN);
4331			spacer = ' ';
4332		}
4333
4334		ireq.i_type = IEEE80211_IOC_UCASTCIPHER;
4335		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4336			LINE_CHECK("ucastcipher ");
4337			printcipher(s, &ireq, IEEE80211_IOC_UCASTKEYLEN);
4338		}
4339
4340		if (wpa & 2) {
4341			ireq.i_type = IEEE80211_IOC_RSNCAPS;
4342			if (ioctl(s, SIOCG80211, &ireq) != -1) {
4343				LINE_CHECK("RSN caps 0x%x", ireq.i_val);
4344				spacer = ' ';
4345			}
4346		}
4347
4348		ireq.i_type = IEEE80211_IOC_UCASTCIPHERS;
4349		if (ioctl(s, SIOCG80211, &ireq) != -1) {
4350		}
4351#endif
4352	}
4353
4354	if (get80211val(s, IEEE80211_IOC_WEP, &wepmode) != -1 &&
4355	    wepmode != IEEE80211_WEP_NOSUP) {
4356		int firstkey;
4357
4358		switch (wepmode) {
4359		case IEEE80211_WEP_OFF:
4360			LINE_CHECK("privacy OFF");
4361			break;
4362		case IEEE80211_WEP_ON:
4363			LINE_CHECK("privacy ON");
4364			break;
4365		case IEEE80211_WEP_MIXED:
4366			LINE_CHECK("privacy MIXED");
4367			break;
4368		default:
4369			LINE_CHECK("privacy UNKNOWN (0x%x)", wepmode);
4370			break;
4371		}
4372
4373		/*
4374		 * If we get here then we've got WEP support so we need
4375		 * to print WEP status.
4376		 */
4377
4378		if (get80211val(s, IEEE80211_IOC_WEPTXKEY, &val) < 0) {
4379			warn("WEP support, but no tx key!");
4380			goto end;
4381		}
4382		if (val != -1)
4383			LINE_CHECK("deftxkey %d", val+1);
4384		else if (wepmode != IEEE80211_WEP_OFF || verbose)
4385			LINE_CHECK("deftxkey UNDEF");
4386
4387		if (get80211val(s, IEEE80211_IOC_NUMWEPKEYS, &num) < 0) {
4388			warn("WEP support, but no NUMWEPKEYS support!");
4389			goto end;
4390		}
4391
4392		firstkey = 1;
4393		for (i = 0; i < num; i++) {
4394			struct ieee80211req_key ik;
4395
4396			memset(&ik, 0, sizeof(ik));
4397			ik.ik_keyix = i;
4398			if (get80211(s, IEEE80211_IOC_WPAKEY, &ik, sizeof(ik)) < 0) {
4399				warn("WEP support, but can get keys!");
4400				goto end;
4401			}
4402			if (ik.ik_keylen != 0) {
4403				if (verbose)
4404					LINE_BREAK();
4405				printkey(&ik);
4406				firstkey = 0;
4407			}
4408		}
4409end:
4410		;
4411	}
4412
4413	if (get80211val(s, IEEE80211_IOC_POWERSAVE, &val) != -1 &&
4414	    val != IEEE80211_POWERSAVE_NOSUP ) {
4415		if (val != IEEE80211_POWERSAVE_OFF || verbose) {
4416			switch (val) {
4417			case IEEE80211_POWERSAVE_OFF:
4418				LINE_CHECK("powersavemode OFF");
4419				break;
4420			case IEEE80211_POWERSAVE_CAM:
4421				LINE_CHECK("powersavemode CAM");
4422				break;
4423			case IEEE80211_POWERSAVE_PSP:
4424				LINE_CHECK("powersavemode PSP");
4425				break;
4426			case IEEE80211_POWERSAVE_PSP_CAM:
4427				LINE_CHECK("powersavemode PSP-CAM");
4428				break;
4429			}
4430			if (get80211val(s, IEEE80211_IOC_POWERSAVESLEEP, &val) != -1)
4431				LINE_CHECK("powersavesleep %d", val);
4432		}
4433	}
4434
4435	if (get80211val(s, IEEE80211_IOC_TXPOWER, &val) != -1) {
4436		if (val & 1)
4437			LINE_CHECK("txpower %d.5", val/2);
4438		else
4439			LINE_CHECK("txpower %d", val/2);
4440	}
4441	if (verbose) {
4442		if (get80211val(s, IEEE80211_IOC_TXPOWMAX, &val) != -1)
4443			LINE_CHECK("txpowmax %.1f", val/2.);
4444	}
4445
4446	if (get80211val(s, IEEE80211_IOC_DOTD, &val) != -1) {
4447		if (val)
4448			LINE_CHECK("dotd");
4449		else if (verbose)
4450			LINE_CHECK("-dotd");
4451	}
4452
4453	if (get80211val(s, IEEE80211_IOC_RTSTHRESHOLD, &val) != -1) {
4454		if (val != IEEE80211_RTS_MAX || verbose)
4455			LINE_CHECK("rtsthreshold %d", val);
4456	}
4457
4458	if (get80211val(s, IEEE80211_IOC_FRAGTHRESHOLD, &val) != -1) {
4459		if (val != IEEE80211_FRAG_MAX || verbose)
4460			LINE_CHECK("fragthreshold %d", val);
4461	}
4462	if (opmode == IEEE80211_M_STA || verbose) {
4463		if (get80211val(s, IEEE80211_IOC_BMISSTHRESHOLD, &val) != -1) {
4464			if (val != IEEE80211_HWBMISS_MAX || verbose)
4465				LINE_CHECK("bmiss %d", val);
4466		}
4467	}
4468
4469	if (!verbose) {
4470		gettxparams(s);
4471		tp = &txparams.params[chan2mode(c)];
4472		printrate("ucastrate", tp->ucastrate,
4473		    IEEE80211_FIXED_RATE_NONE, IEEE80211_FIXED_RATE_NONE);
4474		printrate("mcastrate", tp->mcastrate, 2*1,
4475		    IEEE80211_RATE_MCS|0);
4476		printrate("mgmtrate", tp->mgmtrate, 2*1,
4477		    IEEE80211_RATE_MCS|0);
4478		if (tp->maxretry != 6)		/* XXX */
4479			LINE_CHECK("maxretry %d", tp->maxretry);
4480	} else {
4481		LINE_BREAK();
4482		list_txparams(s);
4483	}
4484
4485	bgscaninterval = -1;
4486	(void) get80211val(s, IEEE80211_IOC_BGSCAN_INTERVAL, &bgscaninterval);
4487
4488	if (get80211val(s, IEEE80211_IOC_SCANVALID, &val) != -1) {
4489		if (val != bgscaninterval || verbose)
4490			LINE_CHECK("scanvalid %u", val);
4491	}
4492
4493	bgscan = 0;
4494	if (get80211val(s, IEEE80211_IOC_BGSCAN, &bgscan) != -1) {
4495		if (bgscan)
4496			LINE_CHECK("bgscan");
4497		else if (verbose)
4498			LINE_CHECK("-bgscan");
4499	}
4500	if (bgscan || verbose) {
4501		if (bgscaninterval != -1)
4502			LINE_CHECK("bgscanintvl %u", bgscaninterval);
4503		if (get80211val(s, IEEE80211_IOC_BGSCAN_IDLE, &val) != -1)
4504			LINE_CHECK("bgscanidle %u", val);
4505		if (!verbose) {
4506			getroam(s);
4507			rp = &roamparams.params[chan2mode(c)];
4508			if (rp->rssi & 1)
4509				LINE_CHECK("roam:rssi %u.5", rp->rssi/2);
4510			else
4511				LINE_CHECK("roam:rssi %u", rp->rssi/2);
4512			LINE_CHECK("roam:rate %u", rp->rate/2);
4513		} else {
4514			LINE_BREAK();
4515			list_roam(s);
4516			LINE_BREAK();
4517		}
4518	}
4519
4520	if (IEEE80211_IS_CHAN_ANYG(c) || verbose) {
4521		if (get80211val(s, IEEE80211_IOC_PUREG, &val) != -1) {
4522			if (val)
4523				LINE_CHECK("pureg");
4524			else if (verbose)
4525				LINE_CHECK("-pureg");
4526		}
4527		if (get80211val(s, IEEE80211_IOC_PROTMODE, &val) != -1) {
4528			switch (val) {
4529			case IEEE80211_PROTMODE_OFF:
4530				LINE_CHECK("protmode OFF");
4531				break;
4532			case IEEE80211_PROTMODE_CTS:
4533				LINE_CHECK("protmode CTS");
4534				break;
4535			case IEEE80211_PROTMODE_RTSCTS:
4536				LINE_CHECK("protmode RTSCTS");
4537				break;
4538			default:
4539				LINE_CHECK("protmode UNKNOWN (0x%x)", val);
4540				break;
4541			}
4542		}
4543	}
4544
4545	if (IEEE80211_IS_CHAN_HT(c) || verbose) {
4546		gethtconf(s);
4547		switch (htconf & 3) {
4548		case 0:
4549		case 2:
4550			LINE_CHECK("-ht");
4551			break;
4552		case 1:
4553			LINE_CHECK("ht20");
4554			break;
4555		case 3:
4556			if (verbose)
4557				LINE_CHECK("ht");
4558			break;
4559		}
4560		if (get80211val(s, IEEE80211_IOC_HTCOMPAT, &val) != -1) {
4561			if (!val)
4562				LINE_CHECK("-htcompat");
4563			else if (verbose)
4564				LINE_CHECK("htcompat");
4565		}
4566		if (get80211val(s, IEEE80211_IOC_AMPDU, &val) != -1) {
4567			switch (val) {
4568			case 0:
4569				LINE_CHECK("-ampdu");
4570				break;
4571			case 1:
4572				LINE_CHECK("ampdutx -ampdurx");
4573				break;
4574			case 2:
4575				LINE_CHECK("-ampdutx ampdurx");
4576				break;
4577			case 3:
4578				if (verbose)
4579					LINE_CHECK("ampdu");
4580				break;
4581			}
4582		}
4583		if (get80211val(s, IEEE80211_IOC_AMPDU_LIMIT, &val) != -1) {
4584			switch (val) {
4585			case IEEE80211_HTCAP_MAXRXAMPDU_8K:
4586				LINE_CHECK("ampdulimit 8k");
4587				break;
4588			case IEEE80211_HTCAP_MAXRXAMPDU_16K:
4589				LINE_CHECK("ampdulimit 16k");
4590				break;
4591			case IEEE80211_HTCAP_MAXRXAMPDU_32K:
4592				LINE_CHECK("ampdulimit 32k");
4593				break;
4594			case IEEE80211_HTCAP_MAXRXAMPDU_64K:
4595				LINE_CHECK("ampdulimit 64k");
4596				break;
4597			}
4598		}
4599		if (get80211val(s, IEEE80211_IOC_AMPDU_DENSITY, &val) != -1) {
4600			switch (val) {
4601			case IEEE80211_HTCAP_MPDUDENSITY_NA:
4602				if (verbose)
4603					LINE_CHECK("ampdudensity NA");
4604				break;
4605			case IEEE80211_HTCAP_MPDUDENSITY_025:
4606				LINE_CHECK("ampdudensity .25");
4607				break;
4608			case IEEE80211_HTCAP_MPDUDENSITY_05:
4609				LINE_CHECK("ampdudensity .5");
4610				break;
4611			case IEEE80211_HTCAP_MPDUDENSITY_1:
4612				LINE_CHECK("ampdudensity 1");
4613				break;
4614			case IEEE80211_HTCAP_MPDUDENSITY_2:
4615				LINE_CHECK("ampdudensity 2");
4616				break;
4617			case IEEE80211_HTCAP_MPDUDENSITY_4:
4618				LINE_CHECK("ampdudensity 4");
4619				break;
4620			case IEEE80211_HTCAP_MPDUDENSITY_8:
4621				LINE_CHECK("ampdudensity 8");
4622				break;
4623			case IEEE80211_HTCAP_MPDUDENSITY_16:
4624				LINE_CHECK("ampdudensity 16");
4625				break;
4626			}
4627		}
4628		if (get80211val(s, IEEE80211_IOC_AMSDU, &val) != -1) {
4629			switch (val) {
4630			case 0:
4631				LINE_CHECK("-amsdu");
4632				break;
4633			case 1:
4634				LINE_CHECK("amsdutx -amsdurx");
4635				break;
4636			case 2:
4637				LINE_CHECK("-amsdutx amsdurx");
4638				break;
4639			case 3:
4640				if (verbose)
4641					LINE_CHECK("amsdu");
4642				break;
4643			}
4644		}
4645		/* XXX amsdu limit */
4646		if (get80211val(s, IEEE80211_IOC_SHORTGI, &val) != -1) {
4647			if (val)
4648				LINE_CHECK("shortgi");
4649			else if (verbose)
4650				LINE_CHECK("-shortgi");
4651		}
4652		if (get80211val(s, IEEE80211_IOC_HTPROTMODE, &val) != -1) {
4653			if (val == IEEE80211_PROTMODE_OFF)
4654				LINE_CHECK("htprotmode OFF");
4655			else if (val != IEEE80211_PROTMODE_RTSCTS)
4656				LINE_CHECK("htprotmode UNKNOWN (0x%x)", val);
4657			else if (verbose)
4658				LINE_CHECK("htprotmode RTSCTS");
4659		}
4660		if (get80211val(s, IEEE80211_IOC_PUREN, &val) != -1) {
4661			if (val)
4662				LINE_CHECK("puren");
4663			else if (verbose)
4664				LINE_CHECK("-puren");
4665		}
4666		if (get80211val(s, IEEE80211_IOC_SMPS, &val) != -1) {
4667			if (val == IEEE80211_HTCAP_SMPS_DYNAMIC)
4668				LINE_CHECK("smpsdyn");
4669			else if (val == IEEE80211_HTCAP_SMPS_ENA)
4670				LINE_CHECK("smps");
4671			else if (verbose)
4672				LINE_CHECK("-smps");
4673		}
4674		if (get80211val(s, IEEE80211_IOC_RIFS, &val) != -1) {
4675			if (val)
4676				LINE_CHECK("rifs");
4677			else if (verbose)
4678				LINE_CHECK("-rifs");
4679		}
4680	}
4681
4682	if (get80211val(s, IEEE80211_IOC_WME, &wme) != -1) {
4683		if (wme)
4684			LINE_CHECK("wme");
4685		else if (verbose)
4686			LINE_CHECK("-wme");
4687	} else
4688		wme = 0;
4689
4690	if (get80211val(s, IEEE80211_IOC_BURST, &val) != -1) {
4691		if (val)
4692			LINE_CHECK("burst");
4693		else if (verbose)
4694			LINE_CHECK("-burst");
4695	}
4696
4697	if (get80211val(s, IEEE80211_IOC_FF, &val) != -1) {
4698		if (val)
4699			LINE_CHECK("ff");
4700		else if (verbose)
4701			LINE_CHECK("-ff");
4702	}
4703	if (get80211val(s, IEEE80211_IOC_TURBOP, &val) != -1) {
4704		if (val)
4705			LINE_CHECK("dturbo");
4706		else if (verbose)
4707			LINE_CHECK("-dturbo");
4708	}
4709	if (get80211val(s, IEEE80211_IOC_DWDS, &val) != -1) {
4710		if (val)
4711			LINE_CHECK("dwds");
4712		else if (verbose)
4713			LINE_CHECK("-dwds");
4714	}
4715
4716	if (opmode == IEEE80211_M_HOSTAP) {
4717		if (get80211val(s, IEEE80211_IOC_HIDESSID, &val) != -1) {
4718			if (val)
4719				LINE_CHECK("hidessid");
4720			else if (verbose)
4721				LINE_CHECK("-hidessid");
4722		}
4723		if (get80211val(s, IEEE80211_IOC_APBRIDGE, &val) != -1) {
4724			if (!val)
4725				LINE_CHECK("-apbridge");
4726			else if (verbose)
4727				LINE_CHECK("apbridge");
4728		}
4729		if (get80211val(s, IEEE80211_IOC_DTIM_PERIOD, &val) != -1)
4730			LINE_CHECK("dtimperiod %u", val);
4731
4732		if (get80211val(s, IEEE80211_IOC_DOTH, &val) != -1) {
4733			if (!val)
4734				LINE_CHECK("-doth");
4735			else if (verbose)
4736				LINE_CHECK("doth");
4737		}
4738		if (get80211val(s, IEEE80211_IOC_DFS, &val) != -1) {
4739			if (!val)
4740				LINE_CHECK("-dfs");
4741			else if (verbose)
4742				LINE_CHECK("dfs");
4743		}
4744		if (get80211val(s, IEEE80211_IOC_INACTIVITY, &val) != -1) {
4745			if (!val)
4746				LINE_CHECK("-inact");
4747			else if (verbose)
4748				LINE_CHECK("inact");
4749		}
4750	} else {
4751		if (get80211val(s, IEEE80211_IOC_ROAMING, &val) != -1) {
4752			if (val != IEEE80211_ROAMING_AUTO || verbose) {
4753				switch (val) {
4754				case IEEE80211_ROAMING_DEVICE:
4755					LINE_CHECK("roaming DEVICE");
4756					break;
4757				case IEEE80211_ROAMING_AUTO:
4758					LINE_CHECK("roaming AUTO");
4759					break;
4760				case IEEE80211_ROAMING_MANUAL:
4761					LINE_CHECK("roaming MANUAL");
4762					break;
4763				default:
4764					LINE_CHECK("roaming UNKNOWN (0x%x)",
4765						val);
4766					break;
4767				}
4768			}
4769		}
4770	}
4771
4772	if (opmode == IEEE80211_M_AHDEMO) {
4773		if (get80211val(s, IEEE80211_IOC_TDMA_SLOT, &val) != -1)
4774			LINE_CHECK("tdmaslot %u", val);
4775		if (get80211val(s, IEEE80211_IOC_TDMA_SLOTCNT, &val) != -1)
4776			LINE_CHECK("tdmaslotcnt %u", val);
4777		if (get80211val(s, IEEE80211_IOC_TDMA_SLOTLEN, &val) != -1)
4778			LINE_CHECK("tdmaslotlen %u", val);
4779		if (get80211val(s, IEEE80211_IOC_TDMA_BINTERVAL, &val) != -1)
4780			LINE_CHECK("tdmabintval %u", val);
4781	} else if (get80211val(s, IEEE80211_IOC_BEACON_INTERVAL, &val) != -1) {
4782		/* XXX default define not visible */
4783		if (val != 100 || verbose)
4784			LINE_CHECK("bintval %u", val);
4785	}
4786
4787	if (wme && verbose) {
4788		LINE_BREAK();
4789		list_wme(s);
4790	}
4791
4792	if (opmode == IEEE80211_M_MBSS) {
4793		if (get80211val(s, IEEE80211_IOC_MESH_TTL, &val) != -1) {
4794			LINE_CHECK("meshttl %u", val);
4795		}
4796		if (get80211val(s, IEEE80211_IOC_MESH_AP, &val) != -1) {
4797			if (val)
4798				LINE_CHECK("meshpeering");
4799			else
4800				LINE_CHECK("-meshpeering");
4801		}
4802		if (get80211val(s, IEEE80211_IOC_MESH_FWRD, &val) != -1) {
4803			if (val)
4804				LINE_CHECK("meshforward");
4805			else
4806				LINE_CHECK("-meshforward");
4807		}
4808		if (get80211len(s, IEEE80211_IOC_MESH_PR_METRIC, data, 12,
4809		    &len) != -1) {
4810			data[len] = '\0';
4811			LINE_CHECK("meshmetric %s", data);
4812		}
4813		if (get80211len(s, IEEE80211_IOC_MESH_PR_PATH, data, 12,
4814		    &len) != -1) {
4815			data[len] = '\0';
4816			LINE_CHECK("meshpath %s", data);
4817		}
4818		if (get80211val(s, IEEE80211_IOC_HWMP_ROOTMODE, &val) != -1) {
4819			switch (val) {
4820			case IEEE80211_HWMP_ROOTMODE_DISABLED:
4821				LINE_CHECK("hwmprootmode DISABLED");
4822				break;
4823			case IEEE80211_HWMP_ROOTMODE_NORMAL:
4824				LINE_CHECK("hwmprootmode NORMAL");
4825				break;
4826			case IEEE80211_HWMP_ROOTMODE_PROACTIVE:
4827				LINE_CHECK("hwmprootmode PROACTIVE");
4828				break;
4829			case IEEE80211_HWMP_ROOTMODE_RANN:
4830				LINE_CHECK("hwmprootmode RANN");
4831				break;
4832			default:
4833				LINE_CHECK("hwmprootmode UNKNOWN(%d)", val);
4834				break;
4835			}
4836		}
4837		if (get80211val(s, IEEE80211_IOC_HWMP_MAXHOPS, &val) != -1) {
4838			LINE_CHECK("hwmpmaxhops %u", val);
4839		}
4840	}
4841
4842	LINE_BREAK();
4843}
4844
4845static int
4846get80211(int s, int type, void *data, int len)
4847{
4848	struct ieee80211req ireq;
4849
4850	(void) memset(&ireq, 0, sizeof(ireq));
4851	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4852	ireq.i_type = type;
4853	ireq.i_data = data;
4854	ireq.i_len = len;
4855	return ioctl(s, SIOCG80211, &ireq);
4856}
4857
4858static int
4859get80211len(int s, int type, void *data, int len, int *plen)
4860{
4861	struct ieee80211req ireq;
4862
4863	(void) memset(&ireq, 0, sizeof(ireq));
4864	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4865	ireq.i_type = type;
4866	ireq.i_len = len;
4867	assert(ireq.i_len == len);	/* NB: check for 16-bit truncation */
4868	ireq.i_data = data;
4869	if (ioctl(s, SIOCG80211, &ireq) < 0)
4870		return -1;
4871	*plen = ireq.i_len;
4872	return 0;
4873}
4874
4875static int
4876get80211val(int s, int type, int *val)
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	if (ioctl(s, SIOCG80211, &ireq) < 0)
4884		return -1;
4885	*val = ireq.i_val;
4886	return 0;
4887}
4888
4889static void
4890set80211(int s, int type, int val, int len, void *data)
4891{
4892	struct ieee80211req	ireq;
4893
4894	(void) memset(&ireq, 0, sizeof(ireq));
4895	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4896	ireq.i_type = type;
4897	ireq.i_val = val;
4898	ireq.i_len = len;
4899	assert(ireq.i_len == len);	/* NB: check for 16-bit truncation */
4900	ireq.i_data = data;
4901	if (ioctl(s, SIOCS80211, &ireq) < 0)
4902		err(1, "SIOCS80211");
4903}
4904
4905static const char *
4906get_string(const char *val, const char *sep, u_int8_t *buf, int *lenp)
4907{
4908	int len;
4909	int hexstr;
4910	u_int8_t *p;
4911
4912	len = *lenp;
4913	p = buf;
4914	hexstr = (val[0] == '0' && tolower((u_char)val[1]) == 'x');
4915	if (hexstr)
4916		val += 2;
4917	for (;;) {
4918		if (*val == '\0')
4919			break;
4920		if (sep != NULL && strchr(sep, *val) != NULL) {
4921			val++;
4922			break;
4923		}
4924		if (hexstr) {
4925			if (!isxdigit((u_char)val[0])) {
4926				warnx("bad hexadecimal digits");
4927				return NULL;
4928			}
4929			if (!isxdigit((u_char)val[1])) {
4930				warnx("odd count hexadecimal digits");
4931				return NULL;
4932			}
4933		}
4934		if (p >= buf + len) {
4935			if (hexstr)
4936				warnx("hexadecimal digits too long");
4937			else
4938				warnx("string too long");
4939			return NULL;
4940		}
4941		if (hexstr) {
4942#define	tohex(x)	(isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
4943			*p++ = (tohex((u_char)val[0]) << 4) |
4944			    tohex((u_char)val[1]);
4945#undef tohex
4946			val += 2;
4947		} else
4948			*p++ = *val++;
4949	}
4950	len = p - buf;
4951	/* The string "-" is treated as the empty string. */
4952	if (!hexstr && len == 1 && buf[0] == '-') {
4953		len = 0;
4954		memset(buf, 0, *lenp);
4955	} else if (len < *lenp)
4956		memset(p, 0, *lenp - len);
4957	*lenp = len;
4958	return val;
4959}
4960
4961static void
4962print_string(const u_int8_t *buf, int len)
4963{
4964	int i;
4965	int hasspc;
4966
4967	i = 0;
4968	hasspc = 0;
4969	for (; i < len; i++) {
4970		if (!isprint(buf[i]) && buf[i] != '\0')
4971			break;
4972		if (isspace(buf[i]))
4973			hasspc++;
4974	}
4975	if (i == len) {
4976		if (hasspc || len == 0 || buf[0] == '\0')
4977			printf("\"%.*s\"", len, buf);
4978		else
4979			printf("%.*s", len, buf);
4980	} else {
4981		printf("0x");
4982		for (i = 0; i < len; i++)
4983			printf("%02x", buf[i]);
4984	}
4985}
4986
4987/*
4988 * Virtual AP cloning support.
4989 */
4990static struct ieee80211_clone_params params = {
4991	.icp_opmode	= IEEE80211_M_STA,	/* default to station mode */
4992};
4993
4994static void
4995wlan_create(int s, struct ifreq *ifr)
4996{
4997	static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
4998
4999	if (params.icp_parent[0] == '\0')
5000		errx(1, "must specify a parent device (wlandev) when creating "
5001		    "a wlan device");
5002	if (params.icp_opmode == IEEE80211_M_WDS &&
5003	    memcmp(params.icp_bssid, zerobssid, sizeof(zerobssid)) == 0)
5004		errx(1, "no bssid specified for WDS (use wlanbssid)");
5005	ifr->ifr_data = (caddr_t) &params;
5006	if (ioctl(s, SIOCIFCREATE2, ifr) < 0)
5007		err(1, "SIOCIFCREATE2");
5008}
5009
5010static
5011DECL_CMD_FUNC(set80211clone_wlandev, arg, d)
5012{
5013	strlcpy(params.icp_parent, arg, IFNAMSIZ);
5014}
5015
5016static
5017DECL_CMD_FUNC(set80211clone_wlanbssid, arg, d)
5018{
5019	const struct ether_addr *ea;
5020
5021	ea = ether_aton(arg);
5022	if (ea == NULL)
5023		errx(1, "%s: cannot parse bssid", arg);
5024	memcpy(params.icp_bssid, ea->octet, IEEE80211_ADDR_LEN);
5025}
5026
5027static
5028DECL_CMD_FUNC(set80211clone_wlanaddr, arg, d)
5029{
5030	const struct ether_addr *ea;
5031
5032	ea = ether_aton(arg);
5033	if (ea == NULL)
5034		errx(1, "%s: cannot parse address", arg);
5035	memcpy(params.icp_macaddr, ea->octet, IEEE80211_ADDR_LEN);
5036	params.icp_flags |= IEEE80211_CLONE_MACADDR;
5037}
5038
5039static
5040DECL_CMD_FUNC(set80211clone_wlanmode, arg, d)
5041{
5042#define	iseq(a,b)	(strncasecmp(a,b,sizeof(b)-1) == 0)
5043	if (iseq(arg, "sta"))
5044		params.icp_opmode = IEEE80211_M_STA;
5045	else if (iseq(arg, "ahdemo") || iseq(arg, "adhoc-demo"))
5046		params.icp_opmode = IEEE80211_M_AHDEMO;
5047	else if (iseq(arg, "ibss") || iseq(arg, "adhoc"))
5048		params.icp_opmode = IEEE80211_M_IBSS;
5049	else if (iseq(arg, "ap") || iseq(arg, "host"))
5050		params.icp_opmode = IEEE80211_M_HOSTAP;
5051	else if (iseq(arg, "wds"))
5052		params.icp_opmode = IEEE80211_M_WDS;
5053	else if (iseq(arg, "monitor"))
5054		params.icp_opmode = IEEE80211_M_MONITOR;
5055	else if (iseq(arg, "tdma")) {
5056		params.icp_opmode = IEEE80211_M_AHDEMO;
5057		params.icp_flags |= IEEE80211_CLONE_TDMA;
5058	} else if (iseq(arg, "mesh") || iseq(arg, "mp")) /* mesh point */
5059		params.icp_opmode = IEEE80211_M_MBSS;
5060	else
5061		errx(1, "Don't know to create %s for %s", arg, name);
5062#undef iseq
5063}
5064
5065static void
5066set80211clone_beacons(const char *val, int d, int s, const struct afswtch *rafp)
5067{
5068	/* NB: inverted sense */
5069	if (d)
5070		params.icp_flags &= ~IEEE80211_CLONE_NOBEACONS;
5071	else
5072		params.icp_flags |= IEEE80211_CLONE_NOBEACONS;
5073}
5074
5075static void
5076set80211clone_bssid(const char *val, int d, int s, const struct afswtch *rafp)
5077{
5078	if (d)
5079		params.icp_flags |= IEEE80211_CLONE_BSSID;
5080	else
5081		params.icp_flags &= ~IEEE80211_CLONE_BSSID;
5082}
5083
5084static void
5085set80211clone_wdslegacy(const char *val, int d, int s, const struct afswtch *rafp)
5086{
5087	if (d)
5088		params.icp_flags |= IEEE80211_CLONE_WDSLEGACY;
5089	else
5090		params.icp_flags &= ~IEEE80211_CLONE_WDSLEGACY;
5091}
5092
5093static struct cmd ieee80211_cmds[] = {
5094	DEF_CMD_ARG("ssid",		set80211ssid),
5095	DEF_CMD_ARG("nwid",		set80211ssid),
5096	DEF_CMD_ARG("meshid",		set80211meshid),
5097	DEF_CMD_ARG("stationname",	set80211stationname),
5098	DEF_CMD_ARG("station",		set80211stationname),	/* BSD/OS */
5099	DEF_CMD_ARG("channel",		set80211channel),
5100	DEF_CMD_ARG("authmode",		set80211authmode),
5101	DEF_CMD_ARG("powersavemode",	set80211powersavemode),
5102	DEF_CMD("powersave",	1,	set80211powersave),
5103	DEF_CMD("-powersave",	0,	set80211powersave),
5104	DEF_CMD_ARG("powersavesleep", 	set80211powersavesleep),
5105	DEF_CMD_ARG("wepmode",		set80211wepmode),
5106	DEF_CMD("wep",		1,	set80211wep),
5107	DEF_CMD("-wep",		0,	set80211wep),
5108	DEF_CMD_ARG("deftxkey",		set80211weptxkey),
5109	DEF_CMD_ARG("weptxkey",		set80211weptxkey),
5110	DEF_CMD_ARG("wepkey",		set80211wepkey),
5111	DEF_CMD_ARG("nwkey",		set80211nwkey),		/* NetBSD */
5112	DEF_CMD("-nwkey",	0,	set80211wep),		/* NetBSD */
5113	DEF_CMD_ARG("rtsthreshold",	set80211rtsthreshold),
5114	DEF_CMD_ARG("protmode",		set80211protmode),
5115	DEF_CMD_ARG("txpower",		set80211txpower),
5116	DEF_CMD_ARG("roaming",		set80211roaming),
5117	DEF_CMD("wme",		1,	set80211wme),
5118	DEF_CMD("-wme",		0,	set80211wme),
5119	DEF_CMD("wmm",		1,	set80211wme),
5120	DEF_CMD("-wmm",		0,	set80211wme),
5121	DEF_CMD("hidessid",	1,	set80211hidessid),
5122	DEF_CMD("-hidessid",	0,	set80211hidessid),
5123	DEF_CMD("apbridge",	1,	set80211apbridge),
5124	DEF_CMD("-apbridge",	0,	set80211apbridge),
5125	DEF_CMD_ARG("chanlist",		set80211chanlist),
5126	DEF_CMD_ARG("bssid",		set80211bssid),
5127	DEF_CMD_ARG("ap",		set80211bssid),
5128	DEF_CMD("scan",	0,		set80211scan),
5129	DEF_CMD_ARG("list",		set80211list),
5130	DEF_CMD_ARG2("cwmin",		set80211cwmin),
5131	DEF_CMD_ARG2("cwmax",		set80211cwmax),
5132	DEF_CMD_ARG2("aifs",		set80211aifs),
5133	DEF_CMD_ARG2("txoplimit",	set80211txoplimit),
5134	DEF_CMD_ARG("acm",		set80211acm),
5135	DEF_CMD_ARG("-acm",		set80211noacm),
5136	DEF_CMD_ARG("ack",		set80211ackpolicy),
5137	DEF_CMD_ARG("-ack",		set80211noackpolicy),
5138	DEF_CMD_ARG2("bss:cwmin",	set80211bsscwmin),
5139	DEF_CMD_ARG2("bss:cwmax",	set80211bsscwmax),
5140	DEF_CMD_ARG2("bss:aifs",	set80211bssaifs),
5141	DEF_CMD_ARG2("bss:txoplimit",	set80211bsstxoplimit),
5142	DEF_CMD_ARG("dtimperiod",	set80211dtimperiod),
5143	DEF_CMD_ARG("bintval",		set80211bintval),
5144	DEF_CMD("mac:open",	IEEE80211_MACCMD_POLICY_OPEN,	set80211maccmd),
5145	DEF_CMD("mac:allow",	IEEE80211_MACCMD_POLICY_ALLOW,	set80211maccmd),
5146	DEF_CMD("mac:deny",	IEEE80211_MACCMD_POLICY_DENY,	set80211maccmd),
5147	DEF_CMD("mac:radius",	IEEE80211_MACCMD_POLICY_RADIUS,	set80211maccmd),
5148	DEF_CMD("mac:flush",	IEEE80211_MACCMD_FLUSH,		set80211maccmd),
5149	DEF_CMD("mac:detach",	IEEE80211_MACCMD_DETACH,	set80211maccmd),
5150	DEF_CMD_ARG("mac:add",		set80211addmac),
5151	DEF_CMD_ARG("mac:del",		set80211delmac),
5152	DEF_CMD_ARG("mac:kick",		set80211kickmac),
5153	DEF_CMD("pureg",	1,	set80211pureg),
5154	DEF_CMD("-pureg",	0,	set80211pureg),
5155	DEF_CMD("ff",		1,	set80211fastframes),
5156	DEF_CMD("-ff",		0,	set80211fastframes),
5157	DEF_CMD("dturbo",	1,	set80211dturbo),
5158	DEF_CMD("-dturbo",	0,	set80211dturbo),
5159	DEF_CMD("bgscan",	1,	set80211bgscan),
5160	DEF_CMD("-bgscan",	0,	set80211bgscan),
5161	DEF_CMD_ARG("bgscanidle",	set80211bgscanidle),
5162	DEF_CMD_ARG("bgscanintvl",	set80211bgscanintvl),
5163	DEF_CMD_ARG("scanvalid",	set80211scanvalid),
5164	DEF_CMD_ARG("roam:rssi",	set80211roamrssi),
5165	DEF_CMD_ARG("roam:rate",	set80211roamrate),
5166	DEF_CMD_ARG("mcastrate",	set80211mcastrate),
5167	DEF_CMD_ARG("ucastrate",	set80211ucastrate),
5168	DEF_CMD_ARG("mgtrate",		set80211mgtrate),
5169	DEF_CMD_ARG("mgmtrate",		set80211mgtrate),
5170	DEF_CMD_ARG("maxretry",		set80211maxretry),
5171	DEF_CMD_ARG("fragthreshold",	set80211fragthreshold),
5172	DEF_CMD("burst",	1,	set80211burst),
5173	DEF_CMD("-burst",	0,	set80211burst),
5174	DEF_CMD_ARG("bmiss",		set80211bmissthreshold),
5175	DEF_CMD_ARG("bmissthreshold",	set80211bmissthreshold),
5176	DEF_CMD("shortgi",	1,	set80211shortgi),
5177	DEF_CMD("-shortgi",	0,	set80211shortgi),
5178	DEF_CMD("ampdurx",	2,	set80211ampdu),
5179	DEF_CMD("-ampdurx",	-2,	set80211ampdu),
5180	DEF_CMD("ampdutx",	1,	set80211ampdu),
5181	DEF_CMD("-ampdutx",	-1,	set80211ampdu),
5182	DEF_CMD("ampdu",	3,	set80211ampdu),		/* NB: tx+rx */
5183	DEF_CMD("-ampdu",	-3,	set80211ampdu),
5184	DEF_CMD_ARG("ampdulimit",	set80211ampdulimit),
5185	DEF_CMD_ARG("ampdudensity",	set80211ampdudensity),
5186	DEF_CMD("amsdurx",	2,	set80211amsdu),
5187	DEF_CMD("-amsdurx",	-2,	set80211amsdu),
5188	DEF_CMD("amsdutx",	1,	set80211amsdu),
5189	DEF_CMD("-amsdutx",	-1,	set80211amsdu),
5190	DEF_CMD("amsdu",	3,	set80211amsdu),		/* NB: tx+rx */
5191	DEF_CMD("-amsdu",	-3,	set80211amsdu),
5192	DEF_CMD_ARG("amsdulimit",	set80211amsdulimit),
5193	DEF_CMD("puren",	1,	set80211puren),
5194	DEF_CMD("-puren",	0,	set80211puren),
5195	DEF_CMD("doth",		1,	set80211doth),
5196	DEF_CMD("-doth",	0,	set80211doth),
5197	DEF_CMD("dfs",		1,	set80211dfs),
5198	DEF_CMD("-dfs",		0,	set80211dfs),
5199	DEF_CMD("htcompat",	1,	set80211htcompat),
5200	DEF_CMD("-htcompat",	0,	set80211htcompat),
5201	DEF_CMD("dwds",		1,	set80211dwds),
5202	DEF_CMD("-dwds",	0,	set80211dwds),
5203	DEF_CMD("inact",	1,	set80211inact),
5204	DEF_CMD("-inact",	0,	set80211inact),
5205	DEF_CMD("tsn",		1,	set80211tsn),
5206	DEF_CMD("-tsn",		0,	set80211tsn),
5207	DEF_CMD_ARG("regdomain",	set80211regdomain),
5208	DEF_CMD_ARG("country",		set80211country),
5209	DEF_CMD("indoor",	'I',	set80211location),
5210	DEF_CMD("-indoor",	'O',	set80211location),
5211	DEF_CMD("outdoor",	'O',	set80211location),
5212	DEF_CMD("-outdoor",	'I',	set80211location),
5213	DEF_CMD("anywhere",	' ',	set80211location),
5214	DEF_CMD("ecm",		1,	set80211ecm),
5215	DEF_CMD("-ecm",		0,	set80211ecm),
5216	DEF_CMD("dotd",		1,	set80211dotd),
5217	DEF_CMD("-dotd",	0,	set80211dotd),
5218	DEF_CMD_ARG("htprotmode",	set80211htprotmode),
5219	DEF_CMD("ht20",		1,	set80211htconf),
5220	DEF_CMD("-ht20",	0,	set80211htconf),
5221	DEF_CMD("ht40",		3,	set80211htconf),	/* NB: 20+40 */
5222	DEF_CMD("-ht40",	0,	set80211htconf),
5223	DEF_CMD("ht",		3,	set80211htconf),	/* NB: 20+40 */
5224	DEF_CMD("-ht",		0,	set80211htconf),
5225	DEF_CMD("rifs",		1,	set80211rifs),
5226	DEF_CMD("-rifs",	0,	set80211rifs),
5227	DEF_CMD("smps",		IEEE80211_HTCAP_SMPS_ENA,	set80211smps),
5228	DEF_CMD("smpsdyn",	IEEE80211_HTCAP_SMPS_DYNAMIC,	set80211smps),
5229	DEF_CMD("-smps",	IEEE80211_HTCAP_SMPS_OFF,	set80211smps),
5230	/* XXX for testing */
5231	DEF_CMD_ARG("chanswitch",	set80211chanswitch),
5232
5233	DEF_CMD_ARG("tdmaslot",		set80211tdmaslot),
5234	DEF_CMD_ARG("tdmaslotcnt",	set80211tdmaslotcnt),
5235	DEF_CMD_ARG("tdmaslotlen",	set80211tdmaslotlen),
5236	DEF_CMD_ARG("tdmabintval",	set80211tdmabintval),
5237
5238	DEF_CMD_ARG("meshttl",		set80211meshttl),
5239	DEF_CMD("meshforward",	1,	set80211meshforward),
5240	DEF_CMD("-meshforward",	0,	set80211meshforward),
5241	DEF_CMD("meshpeering",	1,	set80211meshpeering),
5242	DEF_CMD("-meshpeering",	0,	set80211meshpeering),
5243	DEF_CMD_ARG("meshmetric",	set80211meshmetric),
5244	DEF_CMD_ARG("meshpath",		set80211meshpath),
5245	DEF_CMD("meshrt:flush",	IEEE80211_MESH_RTCMD_FLUSH,	set80211meshrtcmd),
5246	DEF_CMD_ARG("meshrt:add",	set80211addmeshrt),
5247	DEF_CMD_ARG("meshrt:del",	set80211delmeshrt),
5248	DEF_CMD_ARG("hwmprootmode",	set80211hwmprootmode),
5249	DEF_CMD_ARG("hwmpmaxhops",	set80211hwmpmaxhops),
5250
5251	/* vap cloning support */
5252	DEF_CLONE_CMD_ARG("wlanaddr",	set80211clone_wlanaddr),
5253	DEF_CLONE_CMD_ARG("wlanbssid",	set80211clone_wlanbssid),
5254	DEF_CLONE_CMD_ARG("wlandev",	set80211clone_wlandev),
5255	DEF_CLONE_CMD_ARG("wlanmode",	set80211clone_wlanmode),
5256	DEF_CLONE_CMD("beacons", 1,	set80211clone_beacons),
5257	DEF_CLONE_CMD("-beacons", 0,	set80211clone_beacons),
5258	DEF_CLONE_CMD("bssid",	1,	set80211clone_bssid),
5259	DEF_CLONE_CMD("-bssid",	0,	set80211clone_bssid),
5260	DEF_CLONE_CMD("wdslegacy", 1,	set80211clone_wdslegacy),
5261	DEF_CLONE_CMD("-wdslegacy", 0,	set80211clone_wdslegacy),
5262};
5263static struct afswtch af_ieee80211 = {
5264	.af_name	= "af_ieee80211",
5265	.af_af		= AF_UNSPEC,
5266	.af_other_status = ieee80211_status,
5267};
5268
5269static __constructor void
5270ieee80211_ctor(void)
5271{
5272#define	N(a)	(sizeof(a) / sizeof(a[0]))
5273	int i;
5274
5275	for (i = 0; i < N(ieee80211_cmds);  i++)
5276		cmd_register(&ieee80211_cmds[i]);
5277	af_register(&af_ieee80211);
5278	clone_setdefcallback("wlan", wlan_create);
5279#undef N
5280}
5281