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