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