ifieee80211.c revision 183261
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 183261 2008-09-22 00:30:26Z 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			if ((flags & IEEE80211_CHAN_HALF) &&
1774			    (chanFlags & IEEE80211_CHAN_HALF) == 0) {
1775				if (verbose)
1776					printf("%u: skip, device does not support half-rate channels\n", freq);
1777				continue;
1778			}
1779			if ((flags & IEEE80211_CHAN_QUARTER) &&
1780			    (chanFlags & IEEE80211_CHAN_QUARTER) == 0) {
1781				if (verbose)
1782					printf("%u: skip, device does not support quarter-rate channels\n", freq);
1783				continue;
1784			}
1785			if ((flags & IEEE80211_CHAN_HT20) &&
1786			    (chanFlags & IEEE80211_CHAN_HT20) == 0) {
1787				if (verbose)
1788					printf("%u: skip, device does not support HT20 operation\n", freq);
1789				continue;
1790			}
1791			if ((flags & IEEE80211_CHAN_HT40) &&
1792			    (chanFlags & IEEE80211_CHAN_HT40) == 0) {
1793				if (verbose)
1794					printf("%u: skip, device does not support HT40 operation\n", freq);
1795				continue;
1796			}
1797			if ((flags & REQ_ECM) && !reg->ecm) {
1798				if (verbose)
1799					printf("%u: skip, ECM channel\n", freq);
1800				continue;
1801			}
1802			if ((flags & REQ_OUTDOOR) && reg->location == 'I') {
1803				if (verbose)
1804					printf("%u: skip, outdoor channel\n", freq);
1805				continue;
1806			}
1807			if ((flags & IEEE80211_CHAN_HT40) &&
1808			    prev != NULL && (freq - prev->ic_freq) < channelSep) {
1809				if (verbose)
1810					printf("%u: skip, only %u channel "
1811					    "separation, need %d\n", freq,
1812					    freq - prev->ic_freq, channelSep);
1813				continue;
1814			}
1815			if (ci->ic_nchans == IEEE80211_CHAN_MAX) {
1816				if (verbose)
1817					printf("%u: skip, channel table full\n", freq);
1818				break;
1819			}
1820			c = &ci->ic_chans[ci->ic_nchans++];
1821			c->ic_freq = freq;
1822			c->ic_flags = chanFlags |
1823			    (flags &~ (REQ_FLAGS | IEEE80211_CHAN_HT40));
1824			if (c->ic_flags & IEEE80211_CHAN_DFS)
1825				c->ic_maxregpower = nb->maxPowerDFS;
1826			else
1827				c->ic_maxregpower = nb->maxPower;
1828			if (verbose)
1829				printf("[%3d] add freq %u flags 0x%x power %u\n",
1830				    ci->ic_nchans-1, c->ic_freq, c->ic_flags,
1831				    c->ic_maxregpower);
1832			/* NB: kernel fills in other fields */
1833			prev = c;
1834		}
1835	}
1836}
1837
1838static void
1839regdomain_makechannels(
1840	struct ieee80211_regdomain_req *req,
1841	const struct ieee80211_devcaps_req *dc)
1842{
1843	struct regdata *rdp = getregdata();
1844	const struct country *cc;
1845	const struct ieee80211_regdomain *reg = &req->rd;
1846	struct ieee80211req_chaninfo *ci = &req->chaninfo;
1847	const struct regdomain *rd;
1848
1849	/*
1850	 * Locate construction table for new channel list.  We treat
1851	 * the regdomain/SKU as definitive so a country can be in
1852	 * multiple with different properties (e.g. US in FCC+FCC3).
1853	 * If no regdomain is specified then we fallback on the country
1854	 * code to find the associated regdomain since countries always
1855	 * belong to at least one regdomain.
1856	 */
1857	if (reg->regdomain == 0) {
1858		cc = lib80211_country_findbycc(rdp, reg->country);
1859		if (cc == NULL)
1860			errx(1, "internal error, country %d not found",
1861			    reg->country);
1862		rd = cc->rd;
1863	} else
1864		rd = lib80211_regdomain_findbysku(rdp, reg->regdomain);
1865	if (rd == NULL)
1866		errx(1, "internal error, regdomain %d not found",
1867			    reg->regdomain);
1868	if (rd->sku != SKU_DEBUG) {
1869		memset(ci, 0, sizeof(*ci));
1870		if (!LIST_EMPTY(&rd->bands_11b))
1871			regdomain_addchans(ci, &rd->bands_11b, reg,
1872			    IEEE80211_CHAN_B, &dc->dc_chaninfo);
1873		if (!LIST_EMPTY(&rd->bands_11g))
1874			regdomain_addchans(ci, &rd->bands_11g, reg,
1875			    IEEE80211_CHAN_G, &dc->dc_chaninfo);
1876		if (!LIST_EMPTY(&rd->bands_11a))
1877			regdomain_addchans(ci, &rd->bands_11a, reg,
1878			    IEEE80211_CHAN_A, &dc->dc_chaninfo);
1879		if (!LIST_EMPTY(&rd->bands_11na)) {
1880			regdomain_addchans(ci, &rd->bands_11na, reg,
1881			    IEEE80211_CHAN_A | IEEE80211_CHAN_HT20,
1882			    &dc->dc_chaninfo);
1883			regdomain_addchans(ci, &rd->bands_11na, reg,
1884			    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U,
1885			    &dc->dc_chaninfo);
1886			regdomain_addchans(ci, &rd->bands_11na, reg,
1887			    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D,
1888			    &dc->dc_chaninfo);
1889		}
1890		if (!LIST_EMPTY(&rd->bands_11ng)) {
1891			regdomain_addchans(ci, &rd->bands_11ng, reg,
1892			    IEEE80211_CHAN_G | IEEE80211_CHAN_HT20,
1893			    &dc->dc_chaninfo);
1894			regdomain_addchans(ci, &rd->bands_11ng, reg,
1895			    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U,
1896			    &dc->dc_chaninfo);
1897			regdomain_addchans(ci, &rd->bands_11ng, reg,
1898			    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D,
1899			    &dc->dc_chaninfo);
1900		}
1901		qsort(ci->ic_chans, ci->ic_nchans, sizeof(ci->ic_chans[0]),
1902		    regdomain_sort);
1903	} else
1904		*ci = dc->dc_chaninfo;
1905}
1906
1907static void
1908list_countries(void)
1909{
1910	struct regdata *rdp = getregdata();
1911	const struct country *cp;
1912	const struct regdomain *dp;
1913	int i;
1914
1915	i = 0;
1916	printf("\nCountry codes:\n");
1917	LIST_FOREACH(cp, &rdp->countries, next) {
1918		printf("%2s %-15.15s%s", cp->isoname,
1919		    cp->name, ((i+1)%4) == 0 ? "\n" : " ");
1920		i++;
1921	}
1922	i = 0;
1923	printf("\nRegulatory domains:\n");
1924	LIST_FOREACH(dp, &rdp->domains, next) {
1925		printf("%-15.15s%s", dp->name, ((i+1)%4) == 0 ? "\n" : " ");
1926		i++;
1927	}
1928	printf("\n");
1929}
1930
1931static void
1932defaultcountry(const struct regdomain *rd)
1933{
1934	struct regdata *rdp = getregdata();
1935	const struct country *cc;
1936
1937	cc = lib80211_country_findbycc(rdp, rd->cc->code);
1938	if (cc == NULL)
1939		errx(1, "internal error, ISO country code %d not "
1940		    "defined for regdomain %s", rd->cc->code, rd->name);
1941	regdomain.country = cc->code;
1942	regdomain.isocc[0] = cc->isoname[0];
1943	regdomain.isocc[1] = cc->isoname[1];
1944}
1945
1946static
1947DECL_CMD_FUNC(set80211regdomain, val, d)
1948{
1949	struct regdata *rdp = getregdata();
1950	const struct regdomain *rd;
1951
1952	rd = lib80211_regdomain_findbyname(rdp, val);
1953	if (rd == NULL) {
1954		rd = lib80211_regdomain_findbysku(rdp, atoi(val));
1955		if (rd == NULL)
1956			errx(1, "unknown regdomain %s", val);
1957	}
1958	getregdomain(s);
1959	regdomain.regdomain = rd->sku;
1960	if (regdomain.country == 0 && rd->cc != NULL) {
1961		/*
1962		 * No country code setup and there's a default
1963		 * one for this regdomain fill it in.
1964		 */
1965		defaultcountry(rd);
1966	}
1967	callback_register(setregdomain_cb, &regdomain);
1968}
1969
1970static
1971DECL_CMD_FUNC(set80211country, val, d)
1972{
1973	struct regdata *rdp = getregdata();
1974	const struct country *cc;
1975
1976	cc = lib80211_country_findbyname(rdp, val);
1977	if (cc == NULL) {
1978		cc = lib80211_country_findbycc(rdp, atoi(val));
1979		if (cc == NULL)
1980			errx(1, "unknown ISO country code %s", val);
1981	}
1982	getregdomain(s);
1983	regdomain.regdomain = cc->rd->sku;
1984	regdomain.country = cc->code;
1985	regdomain.isocc[0] = cc->isoname[0];
1986	regdomain.isocc[1] = cc->isoname[1];
1987	callback_register(setregdomain_cb, &regdomain);
1988}
1989
1990static void
1991set80211location(const char *val, int d, int s, const struct afswtch *rafp)
1992{
1993	getregdomain(s);
1994	regdomain.location = d;
1995	callback_register(setregdomain_cb, &regdomain);
1996}
1997
1998static void
1999set80211ecm(const char *val, int d, int s, const struct afswtch *rafp)
2000{
2001	getregdomain(s);
2002	regdomain.ecm = d;
2003	callback_register(setregdomain_cb, &regdomain);
2004}
2005
2006static void
2007LINE_INIT(char c)
2008{
2009	spacer = c;
2010	if (c == '\t')
2011		col = 8;
2012	else
2013		col = 1;
2014}
2015
2016static void
2017LINE_BREAK(void)
2018{
2019	if (spacer != '\t') {
2020		printf("\n");
2021		spacer = '\t';
2022	}
2023	col = 8;		/* 8-col tab */
2024}
2025
2026static void
2027LINE_CHECK(const char *fmt, ...)
2028{
2029	char buf[80];
2030	va_list ap;
2031	int n;
2032
2033	va_start(ap, fmt);
2034	n = vsnprintf(buf+1, sizeof(buf)-1, fmt, ap);
2035	va_end(ap);
2036	col += 1+n;
2037	if (col > MAXCOL) {
2038		LINE_BREAK();
2039		col += n;
2040	}
2041	buf[0] = spacer;
2042	printf("%s", buf);
2043	spacer = ' ';
2044}
2045
2046static int
2047getmaxrate(const uint8_t rates[15], uint8_t nrates)
2048{
2049	int i, maxrate = -1;
2050
2051	for (i = 0; i < nrates; i++) {
2052		int rate = rates[i] & IEEE80211_RATE_VAL;
2053		if (rate > maxrate)
2054			maxrate = rate;
2055	}
2056	return maxrate / 2;
2057}
2058
2059static const char *
2060getcaps(int capinfo)
2061{
2062	static char capstring[32];
2063	char *cp = capstring;
2064
2065	if (capinfo & IEEE80211_CAPINFO_ESS)
2066		*cp++ = 'E';
2067	if (capinfo & IEEE80211_CAPINFO_IBSS)
2068		*cp++ = 'I';
2069	if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
2070		*cp++ = 'c';
2071	if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
2072		*cp++ = 'C';
2073	if (capinfo & IEEE80211_CAPINFO_PRIVACY)
2074		*cp++ = 'P';
2075	if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
2076		*cp++ = 'S';
2077	if (capinfo & IEEE80211_CAPINFO_PBCC)
2078		*cp++ = 'B';
2079	if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
2080		*cp++ = 'A';
2081	if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
2082		*cp++ = 's';
2083	if (capinfo & IEEE80211_CAPINFO_RSN)
2084		*cp++ = 'R';
2085	if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
2086		*cp++ = 'D';
2087	*cp = '\0';
2088	return capstring;
2089}
2090
2091static const char *
2092getflags(int flags)
2093{
2094	static char flagstring[32];
2095	char *cp = flagstring;
2096
2097	if (flags & IEEE80211_NODE_AUTH)
2098		*cp++ = 'A';
2099	if (flags & IEEE80211_NODE_QOS)
2100		*cp++ = 'Q';
2101	if (flags & IEEE80211_NODE_ERP)
2102		*cp++ = 'E';
2103	if (flags & IEEE80211_NODE_PWR_MGT)
2104		*cp++ = 'P';
2105	if (flags & IEEE80211_NODE_HT) {
2106		*cp++ = 'H';
2107		if (flags & IEEE80211_NODE_HTCOMPAT)
2108			*cp++ = '+';
2109	}
2110	if (flags & IEEE80211_NODE_WPS)
2111		*cp++ = 'W';
2112	if (flags & IEEE80211_NODE_TSN)
2113		*cp++ = 'N';
2114	if (flags & IEEE80211_NODE_AMPDU_TX)
2115		*cp++ = 'T';
2116	if (flags & IEEE80211_NODE_AMPDU_RX)
2117		*cp++ = 'R';
2118	if (flags & IEEE80211_NODE_MIMO_PS) {
2119		*cp++ = 'M';
2120		if (flags & IEEE80211_NODE_MIMO_RTS)
2121			*cp++ = '+';
2122	}
2123	if (flags & IEEE80211_NODE_RIFS)
2124		*cp++ = 'I';
2125	*cp = '\0';
2126	return flagstring;
2127}
2128
2129static void
2130printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
2131{
2132	printf("%s", tag);
2133	if (verbose) {
2134		maxlen -= strlen(tag)+2;
2135		if (2*ielen > maxlen)
2136			maxlen--;
2137		printf("<");
2138		for (; ielen > 0; ie++, ielen--) {
2139			if (maxlen-- <= 0)
2140				break;
2141			printf("%02x", *ie);
2142		}
2143		if (ielen != 0)
2144			printf("-");
2145		printf(">");
2146	}
2147}
2148
2149#define LE_READ_2(p)					\
2150	((u_int16_t)					\
2151	 ((((const u_int8_t *)(p))[0]      ) |		\
2152	  (((const u_int8_t *)(p))[1] <<  8)))
2153#define LE_READ_4(p)					\
2154	((u_int32_t)					\
2155	 ((((const u_int8_t *)(p))[0]      ) |		\
2156	  (((const u_int8_t *)(p))[1] <<  8) |		\
2157	  (((const u_int8_t *)(p))[2] << 16) |		\
2158	  (((const u_int8_t *)(p))[3] << 24)))
2159
2160/*
2161 * NB: The decoding routines assume a properly formatted ie
2162 *     which should be safe as the kernel only retains them
2163 *     if they parse ok.
2164 */
2165
2166static void
2167printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2168{
2169#define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
2170	static const char *acnames[] = { "BE", "BK", "VO", "VI" };
2171	const struct ieee80211_wme_param *wme =
2172	    (const struct ieee80211_wme_param *) ie;
2173	int i;
2174
2175	printf("%s", tag);
2176	if (!verbose)
2177		return;
2178	printf("<qosinfo 0x%x", wme->param_qosInfo);
2179	ie += offsetof(struct ieee80211_wme_param, params_acParams);
2180	for (i = 0; i < WME_NUM_AC; i++) {
2181		const struct ieee80211_wme_acparams *ac =
2182		    &wme->params_acParams[i];
2183
2184		printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
2185			, acnames[i]
2186			, MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
2187			, MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
2188			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
2189			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
2190			, LE_READ_2(&ac->acp_txop)
2191		);
2192	}
2193	printf(">");
2194#undef MS
2195}
2196
2197static void
2198printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2199{
2200	printf("%s", tag);
2201	if (verbose) {
2202		const struct ieee80211_wme_info *wme =
2203		    (const struct ieee80211_wme_info *) ie;
2204		printf("<version 0x%x info 0x%x>",
2205		    wme->wme_version, wme->wme_info);
2206	}
2207}
2208
2209static void
2210printhtcap(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2211{
2212	printf("%s", tag);
2213	if (verbose) {
2214		const struct ieee80211_ie_htcap *htcap =
2215		    (const struct ieee80211_ie_htcap *) ie;
2216		const char *sep;
2217		int i, j;
2218
2219		printf("<cap 0x%x param 0x%x",
2220		    LE_READ_2(&htcap->hc_cap), htcap->hc_param);
2221		printf(" mcsset[");
2222		sep = "";
2223		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2224			if (isset(htcap->hc_mcsset, i)) {
2225				for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2226					if (isclr(htcap->hc_mcsset, j))
2227						break;
2228				j--;
2229				if (i == j)
2230					printf("%s%u", sep, i);
2231				else
2232					printf("%s%u-%u", sep, i, j);
2233				i += j-i;
2234				sep = ",";
2235			}
2236		printf("] extcap 0x%x txbf 0x%x antenna 0x%x>",
2237		    LE_READ_2(&htcap->hc_extcap),
2238		    LE_READ_4(&htcap->hc_txbf),
2239		    htcap->hc_antenna);
2240	}
2241}
2242
2243static void
2244printhtinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2245{
2246	printf("%s", tag);
2247	if (verbose) {
2248		const struct ieee80211_ie_htinfo *htinfo =
2249		    (const struct ieee80211_ie_htinfo *) ie;
2250		const char *sep;
2251		int i, j;
2252
2253		printf("<ctl %u, %x,%x,%x,%x", htinfo->hi_ctrlchannel,
2254		    htinfo->hi_byte1, htinfo->hi_byte2, htinfo->hi_byte3,
2255		    LE_READ_2(&htinfo->hi_byte45));
2256		printf(" basicmcs[");
2257		sep = "";
2258		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2259			if (isset(htinfo->hi_basicmcsset, i)) {
2260				for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2261					if (isclr(htinfo->hi_basicmcsset, j))
2262						break;
2263				j--;
2264				if (i == j)
2265					printf("%s%u", sep, i);
2266				else
2267					printf("%s%u-%u", sep, i, j);
2268				i += j-i;
2269				sep = ",";
2270			}
2271		printf("]>");
2272	}
2273}
2274
2275static void
2276printathie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2277{
2278
2279	printf("%s", tag);
2280	if (verbose) {
2281		const struct ieee80211_ath_ie *ath =
2282			(const struct ieee80211_ath_ie *)ie;
2283
2284		printf("<");
2285		if (ath->ath_capability & ATHEROS_CAP_TURBO_PRIME)
2286			printf("DTURBO,");
2287		if (ath->ath_capability & ATHEROS_CAP_COMPRESSION)
2288			printf("COMP,");
2289		if (ath->ath_capability & ATHEROS_CAP_FAST_FRAME)
2290			printf("FF,");
2291		if (ath->ath_capability & ATHEROS_CAP_XR)
2292			printf("XR,");
2293		if (ath->ath_capability & ATHEROS_CAP_AR)
2294			printf("AR,");
2295		if (ath->ath_capability & ATHEROS_CAP_BURST)
2296			printf("BURST,");
2297		if (ath->ath_capability & ATHEROS_CAP_WME)
2298			printf("WME,");
2299		if (ath->ath_capability & ATHEROS_CAP_BOOST)
2300			printf("BOOST,");
2301		printf("0x%x>", LE_READ_2(ath->ath_defkeyix));
2302	}
2303}
2304
2305static const char *
2306wpa_cipher(const u_int8_t *sel)
2307{
2308#define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
2309	u_int32_t w = LE_READ_4(sel);
2310
2311	switch (w) {
2312	case WPA_SEL(WPA_CSE_NULL):
2313		return "NONE";
2314	case WPA_SEL(WPA_CSE_WEP40):
2315		return "WEP40";
2316	case WPA_SEL(WPA_CSE_WEP104):
2317		return "WEP104";
2318	case WPA_SEL(WPA_CSE_TKIP):
2319		return "TKIP";
2320	case WPA_SEL(WPA_CSE_CCMP):
2321		return "AES-CCMP";
2322	}
2323	return "?";		/* NB: so 1<< is discarded */
2324#undef WPA_SEL
2325}
2326
2327static const char *
2328wpa_keymgmt(const u_int8_t *sel)
2329{
2330#define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
2331	u_int32_t w = LE_READ_4(sel);
2332
2333	switch (w) {
2334	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
2335		return "8021X-UNSPEC";
2336	case WPA_SEL(WPA_ASE_8021X_PSK):
2337		return "8021X-PSK";
2338	case WPA_SEL(WPA_ASE_NONE):
2339		return "NONE";
2340	}
2341	return "?";
2342#undef WPA_SEL
2343}
2344
2345static void
2346printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2347{
2348	u_int8_t len = ie[1];
2349
2350	printf("%s", tag);
2351	if (verbose) {
2352		const char *sep;
2353		int n;
2354
2355		ie += 6, len -= 4;		/* NB: len is payload only */
2356
2357		printf("<v%u", LE_READ_2(ie));
2358		ie += 2, len -= 2;
2359
2360		printf(" mc:%s", wpa_cipher(ie));
2361		ie += 4, len -= 4;
2362
2363		/* unicast ciphers */
2364		n = LE_READ_2(ie);
2365		ie += 2, len -= 2;
2366		sep = " uc:";
2367		for (; n > 0; n--) {
2368			printf("%s%s", sep, wpa_cipher(ie));
2369			ie += 4, len -= 4;
2370			sep = "+";
2371		}
2372
2373		/* key management algorithms */
2374		n = LE_READ_2(ie);
2375		ie += 2, len -= 2;
2376		sep = " km:";
2377		for (; n > 0; n--) {
2378			printf("%s%s", sep, wpa_keymgmt(ie));
2379			ie += 4, len -= 4;
2380			sep = "+";
2381		}
2382
2383		if (len > 2)		/* optional capabilities */
2384			printf(", caps 0x%x", LE_READ_2(ie));
2385		printf(">");
2386	}
2387}
2388
2389static const char *
2390rsn_cipher(const u_int8_t *sel)
2391{
2392#define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
2393	u_int32_t w = LE_READ_4(sel);
2394
2395	switch (w) {
2396	case RSN_SEL(RSN_CSE_NULL):
2397		return "NONE";
2398	case RSN_SEL(RSN_CSE_WEP40):
2399		return "WEP40";
2400	case RSN_SEL(RSN_CSE_WEP104):
2401		return "WEP104";
2402	case RSN_SEL(RSN_CSE_TKIP):
2403		return "TKIP";
2404	case RSN_SEL(RSN_CSE_CCMP):
2405		return "AES-CCMP";
2406	case RSN_SEL(RSN_CSE_WRAP):
2407		return "AES-OCB";
2408	}
2409	return "?";
2410#undef WPA_SEL
2411}
2412
2413static const char *
2414rsn_keymgmt(const u_int8_t *sel)
2415{
2416#define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
2417	u_int32_t w = LE_READ_4(sel);
2418
2419	switch (w) {
2420	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
2421		return "8021X-UNSPEC";
2422	case RSN_SEL(RSN_ASE_8021X_PSK):
2423		return "8021X-PSK";
2424	case RSN_SEL(RSN_ASE_NONE):
2425		return "NONE";
2426	}
2427	return "?";
2428#undef RSN_SEL
2429}
2430
2431static void
2432printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2433{
2434	printf("%s", tag);
2435	if (verbose) {
2436		const char *sep;
2437		int n;
2438
2439		ie += 2, ielen -= 2;
2440
2441		printf("<v%u", LE_READ_2(ie));
2442		ie += 2, ielen -= 2;
2443
2444		printf(" mc:%s", rsn_cipher(ie));
2445		ie += 4, ielen -= 4;
2446
2447		/* unicast ciphers */
2448		n = LE_READ_2(ie);
2449		ie += 2, ielen -= 2;
2450		sep = " uc:";
2451		for (; n > 0; n--) {
2452			printf("%s%s", sep, rsn_cipher(ie));
2453			ie += 4, ielen -= 4;
2454			sep = "+";
2455		}
2456
2457		/* key management algorithms */
2458		n = LE_READ_2(ie);
2459		ie += 2, ielen -= 2;
2460		sep = " km:";
2461		for (; n > 0; n--) {
2462			printf("%s%s", sep, rsn_keymgmt(ie));
2463			ie += 4, ielen -= 4;
2464			sep = "+";
2465		}
2466
2467		if (ielen > 2)		/* optional capabilities */
2468			printf(", caps 0x%x", LE_READ_2(ie));
2469		/* XXXPMKID */
2470		printf(">");
2471	}
2472}
2473
2474/* XXX move to a public include file */
2475#define IEEE80211_WPS_DEV_PASS_ID	0x1012
2476#define IEEE80211_WPS_SELECTED_REG	0x1041
2477#define IEEE80211_WPS_SETUP_STATE	0x1044
2478#define IEEE80211_WPS_UUID_E		0x1047
2479#define IEEE80211_WPS_VERSION		0x104a
2480
2481#define BE_READ_2(p)					\
2482	((u_int16_t)					\
2483	 ((((const u_int8_t *)(p))[1]      ) |		\
2484	  (((const u_int8_t *)(p))[0] <<  8)))
2485
2486static void
2487printwpsie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2488{
2489#define	N(a)	(sizeof(a) / sizeof(a[0]))
2490	u_int8_t len = ie[1];
2491
2492	printf("%s", tag);
2493	if (verbose) {
2494		static const char *dev_pass_id[] = {
2495			"D",	/* Default (PIN) */
2496			"U",	/* User-specified */
2497			"M",	/* Machine-specified */
2498			"K",	/* Rekey */
2499			"P",	/* PushButton */
2500			"R"	/* Registrar-specified */
2501		};
2502		int n;
2503
2504		ie +=6, len -= 4;		/* NB: len is payload only */
2505
2506		/* WPS IE in Beacon and Probe Resp frames have different fields */
2507		printf("<");
2508		while (len) {
2509			uint16_t tlv_type = BE_READ_2(ie);
2510			uint16_t tlv_len  = BE_READ_2(ie + 2);
2511
2512			ie += 4, len -= 4;
2513
2514			switch (tlv_type) {
2515			case IEEE80211_WPS_VERSION:
2516				printf("v:%d.%d", *ie >> 4, *ie & 0xf);
2517				break;
2518			case IEEE80211_WPS_SETUP_STATE:
2519				/* Only 1 and 2 are valid */
2520				if (*ie == 0 || *ie >= 3)
2521					printf(" state:B");
2522				else
2523					printf(" st:%s", *ie == 1 ? "N" : "C");
2524				break;
2525			case IEEE80211_WPS_SELECTED_REG:
2526				printf(" sel:%s", *ie ? "T" : "F");
2527				break;
2528			case IEEE80211_WPS_DEV_PASS_ID:
2529				n = LE_READ_2(ie);
2530				if (n < N(dev_pass_id))
2531					printf(" dpi:%s", dev_pass_id[n]);
2532				break;
2533			case IEEE80211_WPS_UUID_E:
2534				printf(" uuid-e:");
2535				for (n = 0; n < (tlv_len - 1); n++)
2536					printf("%02x-", ie[n]);
2537				printf("%02x", ie[n]);
2538				break;
2539			}
2540			ie += tlv_len, len -= tlv_len;
2541		}
2542		printf(">");
2543	}
2544#undef N
2545}
2546
2547/*
2548 * Copy the ssid string contents into buf, truncating to fit.  If the
2549 * ssid is entirely printable then just copy intact.  Otherwise convert
2550 * to hexadecimal.  If the result is truncated then replace the last
2551 * three characters with "...".
2552 */
2553static int
2554copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
2555{
2556	const u_int8_t *p;
2557	size_t maxlen;
2558	int i;
2559
2560	if (essid_len > bufsize)
2561		maxlen = bufsize;
2562	else
2563		maxlen = essid_len;
2564	/* determine printable or not */
2565	for (i = 0, p = essid; i < maxlen; i++, p++) {
2566		if (*p < ' ' || *p > 0x7e)
2567			break;
2568	}
2569	if (i != maxlen) {		/* not printable, print as hex */
2570		if (bufsize < 3)
2571			return 0;
2572		strlcpy(buf, "0x", bufsize);
2573		bufsize -= 2;
2574		p = essid;
2575		for (i = 0; i < maxlen && bufsize >= 2; i++) {
2576			sprintf(&buf[2+2*i], "%02x", p[i]);
2577			bufsize -= 2;
2578		}
2579		if (i != essid_len)
2580			memcpy(&buf[2+2*i-3], "...", 3);
2581	} else {			/* printable, truncate as needed */
2582		memcpy(buf, essid, maxlen);
2583		if (maxlen != essid_len)
2584			memcpy(&buf[maxlen-3], "...", 3);
2585	}
2586	return maxlen;
2587}
2588
2589static void
2590printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2591{
2592	char ssid[2*IEEE80211_NWID_LEN+1];
2593
2594	printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
2595}
2596
2597static void
2598printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2599{
2600	const char *sep;
2601	int i;
2602
2603	printf("%s", tag);
2604	sep = "<";
2605	for (i = 2; i < ielen; i++) {
2606		printf("%s%s%d", sep,
2607		    ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
2608		    ie[i] & IEEE80211_RATE_VAL);
2609		sep = ",";
2610	}
2611	printf(">");
2612}
2613
2614static void
2615printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2616{
2617	const struct ieee80211_country_ie *cie =
2618	   (const struct ieee80211_country_ie *) ie;
2619	int i, nbands, schan, nchan;
2620
2621	printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
2622	nbands = (cie->len - 3) / sizeof(cie->band[0]);
2623	for (i = 0; i < nbands; i++) {
2624		schan = cie->band[i].schan;
2625		nchan = cie->band[i].nchan;
2626		if (nchan != 1)
2627			printf(" %u-%u,%u", schan, schan + nchan-1,
2628			    cie->band[i].maxtxpwr);
2629		else
2630			printf(" %u,%u", schan, cie->band[i].maxtxpwr);
2631	}
2632	printf(">");
2633}
2634
2635/* unaligned little endian access */
2636#define LE_READ_4(p)					\
2637	((u_int32_t)					\
2638	 ((((const u_int8_t *)(p))[0]      ) |		\
2639	  (((const u_int8_t *)(p))[1] <<  8) |		\
2640	  (((const u_int8_t *)(p))[2] << 16) |		\
2641	  (((const u_int8_t *)(p))[3] << 24)))
2642
2643static __inline int
2644iswpaoui(const u_int8_t *frm)
2645{
2646	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
2647}
2648
2649static __inline int
2650iswmeinfo(const u_int8_t *frm)
2651{
2652	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
2653		frm[6] == WME_INFO_OUI_SUBTYPE;
2654}
2655
2656static __inline int
2657iswmeparam(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_PARAM_OUI_SUBTYPE;
2661}
2662
2663static __inline int
2664isatherosoui(const u_int8_t *frm)
2665{
2666	return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
2667}
2668
2669static __inline int
2670iswpsoui(const uint8_t *frm)
2671{
2672	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPS_OUI_TYPE<<24)|WPA_OUI);
2673}
2674
2675static const char *
2676iename(int elemid)
2677{
2678	switch (elemid) {
2679	case IEEE80211_ELEMID_FHPARMS:	return " FHPARMS";
2680	case IEEE80211_ELEMID_CFPARMS:	return " CFPARMS";
2681	case IEEE80211_ELEMID_TIM:	return " TIM";
2682	case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
2683	case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
2684	case IEEE80211_ELEMID_PWRCNSTR:	return " PWRCNSTR";
2685	case IEEE80211_ELEMID_PWRCAP:	return " PWRCAP";
2686	case IEEE80211_ELEMID_TPCREQ:	return " TPCREQ";
2687	case IEEE80211_ELEMID_TPCREP:	return " TPCREP";
2688	case IEEE80211_ELEMID_SUPPCHAN:	return " SUPPCHAN";
2689	case IEEE80211_ELEMID_CHANSWITCHANN:return " CSA";
2690	case IEEE80211_ELEMID_MEASREQ:	return " MEASREQ";
2691	case IEEE80211_ELEMID_MEASREP:	return " MEASREP";
2692	case IEEE80211_ELEMID_QUIET:	return " QUIET";
2693	case IEEE80211_ELEMID_IBSSDFS:	return " IBSSDFS";
2694	case IEEE80211_ELEMID_TPC:	return " TPC";
2695	case IEEE80211_ELEMID_CCKM:	return " CCKM";
2696	}
2697	return " ???";
2698}
2699
2700static void
2701printies(const u_int8_t *vp, int ielen, int maxcols)
2702{
2703	while (ielen > 0) {
2704		switch (vp[0]) {
2705		case IEEE80211_ELEMID_SSID:
2706			if (verbose)
2707				printssid(" SSID", vp, 2+vp[1], maxcols);
2708			break;
2709		case IEEE80211_ELEMID_RATES:
2710		case IEEE80211_ELEMID_XRATES:
2711			if (verbose)
2712				printrates(vp[0] == IEEE80211_ELEMID_RATES ?
2713				    " RATES" : " XRATES", vp, 2+vp[1], maxcols);
2714			break;
2715		case IEEE80211_ELEMID_DSPARMS:
2716			if (verbose)
2717				printf(" DSPARMS<%u>", vp[2]);
2718			break;
2719		case IEEE80211_ELEMID_COUNTRY:
2720			if (verbose)
2721				printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
2722			break;
2723		case IEEE80211_ELEMID_ERP:
2724			if (verbose)
2725				printf(" ERP<0x%x>", vp[2]);
2726			break;
2727		case IEEE80211_ELEMID_VENDOR:
2728			if (iswpaoui(vp))
2729				printwpaie(" WPA", vp, 2+vp[1], maxcols);
2730			else if (iswmeinfo(vp))
2731				printwmeinfo(" WME", vp, 2+vp[1], maxcols);
2732			else if (iswmeparam(vp))
2733				printwmeparam(" WME", vp, 2+vp[1], maxcols);
2734			else if (isatherosoui(vp))
2735				printathie(" ATH", vp, 2+vp[1], maxcols);
2736			else if (iswpsoui(vp))
2737				printwpsie(" WPS", vp, 2+vp[1], maxcols);
2738			else if (verbose)
2739				printie(" VEN", vp, 2+vp[1], maxcols);
2740			break;
2741		case IEEE80211_ELEMID_RSN:
2742			printrsnie(" RSN", vp, 2+vp[1], maxcols);
2743			break;
2744		case IEEE80211_ELEMID_HTCAP:
2745			printhtcap(" HTCAP", vp, 2+vp[1], maxcols);
2746			break;
2747		case IEEE80211_ELEMID_HTINFO:
2748			if (verbose)
2749				printhtinfo(" HTINFO", vp, 2+vp[1], maxcols);
2750			break;
2751		default:
2752			if (verbose)
2753				printie(iename(vp[0]), vp, 2+vp[1], maxcols);
2754			break;
2755		}
2756		ielen -= 2+vp[1];
2757		vp += 2+vp[1];
2758	}
2759}
2760
2761static void
2762printmimo(const struct ieee80211_mimo_info *mi)
2763{
2764	/* NB: don't muddy display unless there's something to show */
2765	if (mi->rssi[0] != 0 || mi->rssi[1] != 0 || mi->rssi[2] != 0) {
2766		/* XXX ignore EVM for now */
2767		printf(" (rssi %d:%d:%d nf %d:%d:%d)",
2768		    mi->rssi[0], mi->rssi[1], mi->rssi[2],
2769		    mi->noise[0], mi->noise[1], mi->noise[2]);
2770	}
2771}
2772
2773static void
2774list_scan(int s)
2775{
2776	uint8_t buf[24*1024];
2777	char ssid[IEEE80211_NWID_LEN+1];
2778	const uint8_t *cp;
2779	int len, ssidmax;
2780
2781	if (get80211len(s, IEEE80211_IOC_SCAN_RESULTS, buf, sizeof(buf), &len) < 0)
2782		errx(1, "unable to get scan results");
2783	if (len < sizeof(struct ieee80211req_scan_result))
2784		return;
2785
2786	getchaninfo(s);
2787
2788	ssidmax = verbose ? IEEE80211_NWID_LEN : 14;
2789	printf("%-*.*s  %-17.17s  %4s %4s  %-7s  %3s %4s\n"
2790		, ssidmax, ssidmax, "SSID"
2791		, "BSSID"
2792		, "CHAN"
2793		, "RATE"
2794		, " S:N"
2795		, "INT"
2796		, "CAPS"
2797	);
2798	cp = buf;
2799	do {
2800		const struct ieee80211req_scan_result *sr;
2801		const uint8_t *vp;
2802
2803		sr = (const struct ieee80211req_scan_result *) cp;
2804		vp = cp + sr->isr_ie_off;
2805		printf("%-*.*s  %s  %3d  %3dM %3d:%-3d  %3d %-4.4s"
2806			, ssidmax
2807			  , copy_essid(ssid, ssidmax, vp, sr->isr_ssid_len)
2808			  , ssid
2809			, ether_ntoa((const struct ether_addr *) sr->isr_bssid)
2810			, ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
2811			, getmaxrate(sr->isr_rates, sr->isr_nrates)
2812			, (sr->isr_rssi/2)+sr->isr_noise, sr->isr_noise
2813			, sr->isr_intval
2814			, getcaps(sr->isr_capinfo)
2815		);
2816		printies(vp + sr->isr_ssid_len, sr->isr_ie_len, 24);
2817		printf("\n");
2818		cp += sr->isr_len, len -= sr->isr_len;
2819	} while (len >= sizeof(struct ieee80211req_scan_result));
2820}
2821
2822#ifdef __FreeBSD__
2823#include <net80211/ieee80211_freebsd.h>
2824#endif
2825#ifdef __NetBSD__
2826#include <net80211/ieee80211_netbsd.h>
2827#endif
2828
2829static void
2830scan_and_wait(int s)
2831{
2832	struct ieee80211_scan_req sr;
2833	struct ieee80211req ireq;
2834	int sroute;
2835
2836	sroute = socket(PF_ROUTE, SOCK_RAW, 0);
2837	if (sroute < 0) {
2838		perror("socket(PF_ROUTE,SOCK_RAW)");
2839		return;
2840	}
2841	(void) memset(&ireq, 0, sizeof(ireq));
2842	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
2843	ireq.i_type = IEEE80211_IOC_SCAN_REQ;
2844
2845	memset(&sr, 0, sizeof(sr));
2846	sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE
2847		    | IEEE80211_IOC_SCAN_NOPICK
2848		    | IEEE80211_IOC_SCAN_ONCE;
2849	sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
2850	sr.sr_nssid = 0;
2851
2852	ireq.i_data = &sr;
2853	ireq.i_len = sizeof(sr);
2854	/* NB: only root can trigger a scan so ignore errors */
2855	if (ioctl(s, SIOCS80211, &ireq) >= 0) {
2856		char buf[2048];
2857		struct if_announcemsghdr *ifan;
2858		struct rt_msghdr *rtm;
2859
2860		do {
2861			if (read(sroute, buf, sizeof(buf)) < 0) {
2862				perror("read(PF_ROUTE)");
2863				break;
2864			}
2865			rtm = (struct rt_msghdr *) buf;
2866			if (rtm->rtm_version != RTM_VERSION)
2867				break;
2868			ifan = (struct if_announcemsghdr *) rtm;
2869		} while (rtm->rtm_type != RTM_IEEE80211 ||
2870		    ifan->ifan_what != RTM_IEEE80211_SCAN);
2871	}
2872	close(sroute);
2873}
2874
2875static
2876DECL_CMD_FUNC(set80211scan, val, d)
2877{
2878	scan_and_wait(s);
2879	list_scan(s);
2880}
2881
2882static enum ieee80211_opmode get80211opmode(int s);
2883
2884static int
2885gettxseq(const struct ieee80211req_sta_info *si)
2886{
2887#define	IEEE80211_NODE_QOS	0x0002		/* QoS enabled */
2888
2889	int i, txseq;
2890
2891	if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
2892		return si->isi_txseqs[0];
2893	/* XXX not right but usually what folks want */
2894	txseq = 0;
2895	for (i = 0; i < IEEE80211_TID_SIZE; i++)
2896		if (si->isi_txseqs[i] > txseq)
2897			txseq = si->isi_txseqs[i];
2898	return txseq;
2899#undef IEEE80211_NODE_QOS
2900}
2901
2902static int
2903getrxseq(const struct ieee80211req_sta_info *si)
2904{
2905#define	IEEE80211_NODE_QOS	0x0002		/* QoS enabled */
2906
2907	int i, rxseq;
2908
2909	if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
2910		return si->isi_rxseqs[0];
2911	/* XXX not right but usually what folks want */
2912	rxseq = 0;
2913	for (i = 0; i < IEEE80211_TID_SIZE; i++)
2914		if (si->isi_rxseqs[i] > rxseq)
2915			rxseq = si->isi_rxseqs[i];
2916	return rxseq;
2917#undef IEEE80211_NODE_QOS
2918}
2919
2920static void
2921list_stations(int s)
2922{
2923	union {
2924		struct ieee80211req_sta_req req;
2925		uint8_t buf[24*1024];
2926	} u;
2927	enum ieee80211_opmode opmode = get80211opmode(s);
2928	const uint8_t *cp;
2929	int len;
2930
2931	/* broadcast address =>'s get all stations */
2932	(void) memset(u.req.is_u.macaddr, 0xff, IEEE80211_ADDR_LEN);
2933	if (opmode == IEEE80211_M_STA) {
2934		/*
2935		 * Get information about the associated AP.
2936		 */
2937		(void) get80211(s, IEEE80211_IOC_BSSID,
2938		    u.req.is_u.macaddr, IEEE80211_ADDR_LEN);
2939	}
2940	if (get80211len(s, IEEE80211_IOC_STA_INFO, &u, sizeof(u), &len) < 0)
2941		errx(1, "unable to get station information");
2942	if (len < sizeof(struct ieee80211req_sta_info))
2943		return;
2944
2945	getchaninfo(s);
2946
2947	printf("%-17.17s %4s %4s %4s %4s %4s %6s %6s %4s %4s\n"
2948		, "ADDR"
2949		, "AID"
2950		, "CHAN"
2951		, "RATE"
2952		, "RSSI"
2953		, "IDLE"
2954		, "TXSEQ"
2955		, "RXSEQ"
2956		, "CAPS"
2957		, "FLAG"
2958	);
2959	cp = (const uint8_t *) u.req.info;
2960	do {
2961		const struct ieee80211req_sta_info *si;
2962
2963		si = (const struct ieee80211req_sta_info *) cp;
2964		if (si->isi_len < sizeof(*si))
2965			break;
2966		printf("%s %4u %4d %3dM %3.1f %4d %6d %6d %-4.4s %-4.4s"
2967			, ether_ntoa((const struct ether_addr*) si->isi_macaddr)
2968			, IEEE80211_AID(si->isi_associd)
2969			, ieee80211_mhz2ieee(si->isi_freq, si->isi_flags)
2970			, si->isi_txmbps/2
2971			, si->isi_rssi/2.
2972			, si->isi_inact
2973			, gettxseq(si)
2974			, getrxseq(si)
2975			, getcaps(si->isi_capinfo)
2976			, getflags(si->isi_state)
2977		);
2978		printies(cp + si->isi_ie_off, si->isi_ie_len, 24);
2979		printmimo(&si->isi_mimo);
2980		printf("\n");
2981		cp += si->isi_len, len -= si->isi_len;
2982	} while (len >= sizeof(struct ieee80211req_sta_info));
2983}
2984
2985static const char *
2986get_chaninfo(const struct ieee80211_channel *c, int precise,
2987	char buf[], size_t bsize)
2988{
2989	buf[0] = '\0';
2990	if (IEEE80211_IS_CHAN_FHSS(c))
2991		strlcat(buf, " FHSS", bsize);
2992	if (IEEE80211_IS_CHAN_A(c)) {
2993		if (IEEE80211_IS_CHAN_HALF(c))
2994			strlcat(buf, " 11a/10Mhz", bsize);
2995		else if (IEEE80211_IS_CHAN_QUARTER(c))
2996			strlcat(buf, " 11a/5Mhz", bsize);
2997		else
2998			strlcat(buf, " 11a", bsize);
2999	}
3000	if (IEEE80211_IS_CHAN_ANYG(c)) {
3001		if (IEEE80211_IS_CHAN_HALF(c))
3002			strlcat(buf, " 11g/10Mhz", bsize);
3003		else if (IEEE80211_IS_CHAN_QUARTER(c))
3004			strlcat(buf, " 11g/5Mhz", bsize);
3005		else
3006			strlcat(buf, " 11g", bsize);
3007	} else if (IEEE80211_IS_CHAN_B(c))
3008		strlcat(buf, " 11b", bsize);
3009	if (IEEE80211_IS_CHAN_TURBO(c))
3010		strlcat(buf, " Turbo", bsize);
3011	if (precise) {
3012		if (IEEE80211_IS_CHAN_HT20(c))
3013			strlcat(buf, " ht/20", bsize);
3014		else if (IEEE80211_IS_CHAN_HT40D(c))
3015			strlcat(buf, " ht/40-", bsize);
3016		else if (IEEE80211_IS_CHAN_HT40U(c))
3017			strlcat(buf, " ht/40+", bsize);
3018	} else {
3019		if (IEEE80211_IS_CHAN_HT(c))
3020			strlcat(buf, " ht", bsize);
3021	}
3022	return buf;
3023}
3024
3025static void
3026print_chaninfo(const struct ieee80211_channel *c, int verb)
3027{
3028	char buf[14];
3029
3030	printf("Channel %3u : %u%c Mhz%-14.14s",
3031		ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3032		IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3033		get_chaninfo(c, verb, buf, sizeof(buf)));
3034}
3035
3036static void
3037print_channels(int s, const struct ieee80211req_chaninfo *chans,
3038	int allchans, int verb)
3039{
3040	struct ieee80211req_chaninfo achans;
3041	uint8_t reported[IEEE80211_CHAN_BYTES];
3042	const struct ieee80211_channel *c;
3043	int i, half;
3044
3045	memset(&achans, 0, sizeof(achans));
3046	memset(reported, 0, sizeof(reported));
3047	if (!allchans) {
3048		struct ieee80211req_chanlist active;
3049
3050		if (get80211(s, IEEE80211_IOC_CHANLIST, &active, sizeof(active)) < 0)
3051			errx(1, "unable to get active channel list");
3052		memset(&achans, 0, sizeof(achans));
3053		for (i = 0; i < chans->ic_nchans; i++) {
3054			c = &chans->ic_chans[i];
3055			if (!isset(active.ic_channels, c->ic_ieee))
3056				continue;
3057			/*
3058			 * Suppress compatible duplicates unless
3059			 * verbose.  The kernel gives us it's
3060			 * complete channel list which has separate
3061			 * entries for 11g/11b and 11a/turbo.
3062			 */
3063			if (isset(reported, c->ic_ieee) && !verb) {
3064				/* XXX we assume duplicates are adjacent */
3065				achans.ic_chans[achans.ic_nchans-1] = *c;
3066			} else {
3067				achans.ic_chans[achans.ic_nchans++] = *c;
3068				setbit(reported, c->ic_ieee);
3069			}
3070		}
3071	} else {
3072		for (i = 0; i < chans->ic_nchans; i++) {
3073			c = &chans->ic_chans[i];
3074			/* suppress duplicates as above */
3075			if (isset(reported, c->ic_ieee) && !verb) {
3076				/* XXX we assume duplicates are adjacent */
3077				achans.ic_chans[achans.ic_nchans-1] = *c;
3078			} else {
3079				achans.ic_chans[achans.ic_nchans++] = *c;
3080				setbit(reported, c->ic_ieee);
3081			}
3082		}
3083	}
3084	half = achans.ic_nchans / 2;
3085	if (achans.ic_nchans % 2)
3086		half++;
3087
3088	for (i = 0; i < achans.ic_nchans / 2; i++) {
3089		print_chaninfo(&achans.ic_chans[i], verb);
3090		print_chaninfo(&achans.ic_chans[half+i], verb);
3091		printf("\n");
3092	}
3093	if (achans.ic_nchans % 2) {
3094		print_chaninfo(&achans.ic_chans[i], verb);
3095		printf("\n");
3096	}
3097}
3098
3099static void
3100list_channels(int s, int allchans)
3101{
3102	getchaninfo(s);
3103	print_channels(s, &chaninfo, allchans, verbose);
3104}
3105
3106static void
3107print_txpow(const struct ieee80211_channel *c)
3108{
3109	printf("Channel %3u : %u Mhz %3.1f reg %2d  ",
3110	    c->ic_ieee, c->ic_freq,
3111	    c->ic_maxpower/2., c->ic_maxregpower);
3112}
3113
3114static void
3115print_txpow_verbose(const struct ieee80211_channel *c)
3116{
3117	print_chaninfo(c, 1);
3118	printf("min %4.1f dBm  max %3.1f dBm  reg %2d dBm",
3119	    c->ic_minpower/2., c->ic_maxpower/2., c->ic_maxregpower);
3120	/* indicate where regulatory cap limits power use */
3121	if (c->ic_maxpower > 2*c->ic_maxregpower)
3122		printf(" <");
3123}
3124
3125static void
3126list_txpow(int s)
3127{
3128	struct ieee80211req_chaninfo achans;
3129	uint8_t reported[IEEE80211_CHAN_BYTES];
3130	struct ieee80211_channel *c, *prev;
3131	int i, half;
3132
3133	getchaninfo(s);
3134	memset(&achans, 0, sizeof(achans));
3135	memset(reported, 0, sizeof(reported));
3136	for (i = 0; i < chaninfo.ic_nchans; i++) {
3137		c = &chaninfo.ic_chans[i];
3138		/* suppress duplicates as above */
3139		if (isset(reported, c->ic_ieee) && !verbose) {
3140			/* XXX we assume duplicates are adjacent */
3141			prev = &achans.ic_chans[achans.ic_nchans-1];
3142			/* display highest power on channel */
3143			if (c->ic_maxpower > prev->ic_maxpower)
3144				*prev = *c;
3145		} else {
3146			achans.ic_chans[achans.ic_nchans++] = *c;
3147			setbit(reported, c->ic_ieee);
3148		}
3149	}
3150	if (!verbose) {
3151		half = achans.ic_nchans / 2;
3152		if (achans.ic_nchans % 2)
3153			half++;
3154
3155		for (i = 0; i < achans.ic_nchans / 2; i++) {
3156			print_txpow(&achans.ic_chans[i]);
3157			print_txpow(&achans.ic_chans[half+i]);
3158			printf("\n");
3159		}
3160		if (achans.ic_nchans % 2) {
3161			print_txpow(&achans.ic_chans[i]);
3162			printf("\n");
3163		}
3164	} else {
3165		for (i = 0; i < achans.ic_nchans; i++) {
3166			print_txpow_verbose(&achans.ic_chans[i]);
3167			printf("\n");
3168		}
3169	}
3170}
3171
3172static void
3173list_keys(int s)
3174{
3175}
3176
3177#define	IEEE80211_C_BITS \
3178	"\20\1STA\7FF\10TURBOP\11IBSS\12PMGT" \
3179	"\13HOSTAP\14AHDEMO\15SWRETRY\16TXPMGT\17SHSLOT\20SHPREAMBLE" \
3180	"\21MONITOR\22DFS\30WPA1\31WPA2\32BURST\33WME\34WDS\36BGSCAN" \
3181	"\37TXFRAG"
3182
3183#define	IEEE80211_CRYPTO_BITS \
3184	"\20\1WEP\2TKIP\3AES\4AES_CCM\5TKIPMIC\6CKIP\12PMGT"
3185
3186#define	IEEE80211_HTCAP_BITS \
3187	"\20\1LDPC\2CHWIDTH40\5GREENFIELD\6SHORTGI20\7SHORTGI40\10TXSTBC" \
3188	"\21AMPDU\22AMSDU\23HT"
3189
3190static void
3191list_capabilities(int s)
3192{
3193	struct ieee80211_devcaps_req dc;
3194
3195	getdevcaps(s, &dc);
3196	printb("drivercaps", dc.dc_drivercaps, IEEE80211_C_BITS);
3197	if (dc.dc_cryptocaps != 0 || verbose) {
3198		putchar('\n');
3199		printb("cryptocaps", dc.dc_cryptocaps, IEEE80211_CRYPTO_BITS);
3200	}
3201	if (dc.dc_htcaps != 0 || verbose) {
3202		putchar('\n');
3203		printb("htcaps", dc.dc_htcaps, IEEE80211_HTCAP_BITS);
3204	}
3205	putchar('\n');
3206}
3207
3208static int
3209get80211wme(int s, int param, int ac, int *val)
3210{
3211	struct ieee80211req ireq;
3212
3213	(void) memset(&ireq, 0, sizeof(ireq));
3214	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3215	ireq.i_type = param;
3216	ireq.i_len = ac;
3217	if (ioctl(s, SIOCG80211, &ireq) < 0) {
3218		warn("cannot get WME parameter %d, ac %d%s",
3219		    param, ac & IEEE80211_WMEPARAM_VAL,
3220		    ac & IEEE80211_WMEPARAM_BSS ? " (BSS)" : "");
3221		return -1;
3222	}
3223	*val = ireq.i_val;
3224	return 0;
3225}
3226
3227static void
3228list_wme_aci(int s, const char *tag, int ac)
3229{
3230	int val;
3231
3232	printf("\t%s", tag);
3233
3234	/* show WME BSS parameters */
3235	if (get80211wme(s, IEEE80211_IOC_WME_CWMIN, ac, &val) != -1)
3236		printf(" cwmin %2u", val);
3237	if (get80211wme(s, IEEE80211_IOC_WME_CWMAX, ac, &val) != -1)
3238		printf(" cwmax %2u", val);
3239	if (get80211wme(s, IEEE80211_IOC_WME_AIFS, ac, &val) != -1)
3240		printf(" aifs %2u", val);
3241	if (get80211wme(s, IEEE80211_IOC_WME_TXOPLIMIT, ac, &val) != -1)
3242		printf(" txopLimit %3u", val);
3243	if (get80211wme(s, IEEE80211_IOC_WME_ACM, ac, &val) != -1) {
3244		if (val)
3245			printf(" acm");
3246		else if (verbose)
3247			printf(" -acm");
3248	}
3249	/* !BSS only */
3250	if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
3251		if (get80211wme(s, IEEE80211_IOC_WME_ACKPOLICY, ac, &val) != -1) {
3252			if (!val)
3253				printf(" -ack");
3254			else if (verbose)
3255				printf(" ack");
3256		}
3257	}
3258	printf("\n");
3259}
3260
3261static void
3262list_wme(int s)
3263{
3264	static const char *acnames[] = { "AC_BE", "AC_BK", "AC_VI", "AC_VO" };
3265	int ac;
3266
3267	if (verbose) {
3268		/* display both BSS and local settings */
3269		for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++) {
3270	again:
3271			if (ac & IEEE80211_WMEPARAM_BSS)
3272				list_wme_aci(s, "     ", ac);
3273			else
3274				list_wme_aci(s, acnames[ac], ac);
3275			if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
3276				ac |= IEEE80211_WMEPARAM_BSS;
3277				goto again;
3278			} else
3279				ac &= ~IEEE80211_WMEPARAM_BSS;
3280		}
3281	} else {
3282		/* display only channel settings */
3283		for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++)
3284			list_wme_aci(s, acnames[ac], ac);
3285	}
3286}
3287
3288static void
3289list_roam(int s)
3290{
3291	const struct ieee80211_roamparam *rp;
3292	int mode;
3293
3294	getroam(s);
3295	for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_11NA; mode++) {
3296		rp = &roamparams.params[mode];
3297		if (rp->rssi == 0 && rp->rate == 0)
3298			continue;
3299		if (rp->rssi & 1)
3300			LINE_CHECK("roam:%-6.6s rssi %2u.5dBm rate %2u Mb/s",
3301			    modename[mode], rp->rssi/2, rp->rate/2);
3302		else
3303			LINE_CHECK("roam:%-6.6s rssi %4udBm rate %2u Mb/s",
3304			    modename[mode], rp->rssi/2, rp->rate/2);
3305	}
3306	for (; mode < IEEE80211_MODE_MAX; mode++) {
3307		rp = &roamparams.params[mode];
3308		if (rp->rssi == 0 && rp->rate == 0)
3309			continue;
3310		if (rp->rssi & 1)
3311			LINE_CHECK("roam:%-6.6s rssi %2u.5dBm  MCS %2u    ",
3312			    modename[mode], rp->rssi/2, rp->rate &~ 0x80);
3313		else
3314			LINE_CHECK("roam:%-6.6s rssi %4udBm  MCS %2u    ",
3315			    modename[mode], rp->rssi/2, rp->rate &~ 0x80);
3316	}
3317}
3318
3319static void
3320list_txparams(int s)
3321{
3322	const struct ieee80211_txparam *tp;
3323	int mode;
3324
3325	gettxparams(s);
3326	for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_11NA; mode++) {
3327		tp = &txparams.params[mode];
3328		if (tp->mgmtrate == 0 && tp->mcastrate == 0)
3329			continue;
3330		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
3331			LINE_CHECK("%-6.6s ucast NONE    mgmt %2u Mb/s "
3332			    "mcast %2u Mb/s maxretry %u",
3333			    modename[mode], tp->mgmtrate/2,
3334			    tp->mcastrate/2, tp->maxretry);
3335		else
3336			LINE_CHECK("%-6.6s ucast %2u Mb/s mgmt %2u Mb/s "
3337			    "mcast %2u Mb/s maxretry %u",
3338			    modename[mode], tp->ucastrate/2, tp->mgmtrate/2,
3339			    tp->mcastrate/2, tp->maxretry);
3340	}
3341	for (; mode < IEEE80211_MODE_MAX; mode++) {
3342		tp = &txparams.params[mode];
3343		if (tp->mgmtrate == 0 && tp->mcastrate == 0)
3344			continue;
3345		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
3346			LINE_CHECK("%-6.6s ucast NONE    mgmt %2u MCS  "
3347			    "mcast %2u MCS  maxretry %u",
3348			    modename[mode], tp->mgmtrate &~ 0x80,
3349			    tp->mcastrate &~ 0x80, tp->maxretry);
3350		else
3351			LINE_CHECK("%-6.6s ucast %2u MCS  mgmt %2u MCS  "
3352			    "mcast %2u MCS  maxretry %u",
3353			    modename[mode], tp->ucastrate &~ 0x80,
3354			    tp->mgmtrate &~ 0x80,
3355			    tp->mcastrate &~ 0x80, tp->maxretry);
3356	}
3357}
3358
3359static void
3360printpolicy(int policy)
3361{
3362	switch (policy) {
3363	case IEEE80211_MACCMD_POLICY_OPEN:
3364		printf("policy: open\n");
3365		break;
3366	case IEEE80211_MACCMD_POLICY_ALLOW:
3367		printf("policy: allow\n");
3368		break;
3369	case IEEE80211_MACCMD_POLICY_DENY:
3370		printf("policy: deny\n");
3371		break;
3372	case IEEE80211_MACCMD_POLICY_RADIUS:
3373		printf("policy: radius\n");
3374		break;
3375	default:
3376		printf("policy: unknown (%u)\n", policy);
3377		break;
3378	}
3379}
3380
3381static void
3382list_mac(int s)
3383{
3384	struct ieee80211req ireq;
3385	struct ieee80211req_maclist *acllist;
3386	int i, nacls, policy, len;
3387	uint8_t *data;
3388	char c;
3389
3390	(void) memset(&ireq, 0, sizeof(ireq));
3391	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name)); /* XXX ?? */
3392	ireq.i_type = IEEE80211_IOC_MACCMD;
3393	ireq.i_val = IEEE80211_MACCMD_POLICY;
3394	if (ioctl(s, SIOCG80211, &ireq) < 0) {
3395		if (errno == EINVAL) {
3396			printf("No acl policy loaded\n");
3397			return;
3398		}
3399		err(1, "unable to get mac policy");
3400	}
3401	policy = ireq.i_val;
3402	if (policy == IEEE80211_MACCMD_POLICY_OPEN) {
3403		c = '*';
3404	} else if (policy == IEEE80211_MACCMD_POLICY_ALLOW) {
3405		c = '+';
3406	} else if (policy == IEEE80211_MACCMD_POLICY_DENY) {
3407		c = '-';
3408	} else if (policy == IEEE80211_MACCMD_POLICY_RADIUS) {
3409		c = 'r';		/* NB: should never have entries */
3410	} else {
3411		printf("policy: unknown (%u)\n", policy);
3412		c = '?';
3413	}
3414	if (verbose || c == '?')
3415		printpolicy(policy);
3416
3417	ireq.i_val = IEEE80211_MACCMD_LIST;
3418	ireq.i_len = 0;
3419	if (ioctl(s, SIOCG80211, &ireq) < 0)
3420		err(1, "unable to get mac acl list size");
3421	if (ireq.i_len == 0) {		/* NB: no acls */
3422		if (!(verbose || c == '?'))
3423			printpolicy(policy);
3424		return;
3425	}
3426	len = ireq.i_len;
3427
3428	data = malloc(len);
3429	if (data == NULL)
3430		err(1, "out of memory for acl list");
3431
3432	ireq.i_data = data;
3433	if (ioctl(s, SIOCG80211, &ireq) < 0)
3434		err(1, "unable to get mac acl list");
3435	nacls = len / sizeof(*acllist);
3436	acllist = (struct ieee80211req_maclist *) data;
3437	for (i = 0; i < nacls; i++)
3438		printf("%c%s\n", c, ether_ntoa(
3439			(const struct ether_addr *) acllist[i].ml_macaddr));
3440	free(data);
3441}
3442
3443static void
3444print_regdomain(const struct ieee80211_regdomain *reg, int verb)
3445{
3446	if ((reg->regdomain != 0 &&
3447	    reg->regdomain != reg->country) || verb) {
3448		const struct regdomain *rd =
3449		    lib80211_regdomain_findbysku(getregdata(), reg->regdomain);
3450		if (rd == NULL)
3451			LINE_CHECK("regdomain %d", reg->regdomain);
3452		else
3453			LINE_CHECK("regdomain %s", rd->name);
3454	}
3455	if (reg->country != 0 || verb) {
3456		const struct country *cc =
3457		    lib80211_country_findbycc(getregdata(), reg->country);
3458		if (cc == NULL)
3459			LINE_CHECK("country %d", reg->country);
3460		else
3461			LINE_CHECK("country %s", cc->isoname);
3462	}
3463	if (reg->location == 'I')
3464		LINE_CHECK("indoor");
3465	else if (reg->location == 'O')
3466		LINE_CHECK("outdoor");
3467	else if (verb)
3468		LINE_CHECK("anywhere");
3469	if (reg->ecm)
3470		LINE_CHECK("ecm");
3471	else if (verb)
3472		LINE_CHECK("-ecm");
3473}
3474
3475static void
3476list_regdomain(int s, int channelsalso)
3477{
3478	getregdomain(s);
3479	if (channelsalso) {
3480		getchaninfo(s);
3481		spacer = ':';
3482		print_regdomain(&regdomain, 1);
3483		LINE_BREAK();
3484		print_channels(s, &chaninfo, 1/*allchans*/, 1/*verbose*/);
3485	} else
3486		print_regdomain(&regdomain, verbose);
3487}
3488
3489static
3490DECL_CMD_FUNC(set80211list, arg, d)
3491{
3492#define	iseq(a,b)	(strncasecmp(a,b,sizeof(b)-1) == 0)
3493
3494	LINE_INIT('\t');
3495
3496	if (iseq(arg, "sta"))
3497		list_stations(s);
3498	else if (iseq(arg, "scan") || iseq(arg, "ap"))
3499		list_scan(s);
3500	else if (iseq(arg, "chan") || iseq(arg, "freq"))
3501		list_channels(s, 1);
3502	else if (iseq(arg, "active"))
3503		list_channels(s, 0);
3504	else if (iseq(arg, "keys"))
3505		list_keys(s);
3506	else if (iseq(arg, "caps"))
3507		list_capabilities(s);
3508	else if (iseq(arg, "wme") || iseq(arg, "wmm"))
3509		list_wme(s);
3510	else if (iseq(arg, "mac"))
3511		list_mac(s);
3512	else if (iseq(arg, "txpow"))
3513		list_txpow(s);
3514	else if (iseq(arg, "roam"))
3515		list_roam(s);
3516	else if (iseq(arg, "txparam") || iseq(arg, "txparm"))
3517		list_txparams(s);
3518	else if (iseq(arg, "regdomain"))
3519		list_regdomain(s, 1);
3520	else if (iseq(arg, "countries"))
3521		list_countries();
3522	else
3523		errx(1, "Don't know how to list %s for %s", arg, name);
3524	LINE_BREAK();
3525#undef iseq
3526}
3527
3528static enum ieee80211_opmode
3529get80211opmode(int s)
3530{
3531	struct ifmediareq ifmr;
3532
3533	(void) memset(&ifmr, 0, sizeof(ifmr));
3534	(void) strncpy(ifmr.ifm_name, name, sizeof(ifmr.ifm_name));
3535
3536	if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0) {
3537		if (ifmr.ifm_current & IFM_IEEE80211_ADHOC)
3538			return IEEE80211_M_IBSS;	/* XXX ahdemo */
3539		if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
3540			return IEEE80211_M_HOSTAP;
3541		if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
3542			return IEEE80211_M_MONITOR;
3543	}
3544	return IEEE80211_M_STA;
3545}
3546
3547#if 0
3548static void
3549printcipher(int s, struct ieee80211req *ireq, int keylenop)
3550{
3551	switch (ireq->i_val) {
3552	case IEEE80211_CIPHER_WEP:
3553		ireq->i_type = keylenop;
3554		if (ioctl(s, SIOCG80211, ireq) != -1)
3555			printf("WEP-%s",
3556			    ireq->i_len <= 5 ? "40" :
3557			    ireq->i_len <= 13 ? "104" : "128");
3558		else
3559			printf("WEP");
3560		break;
3561	case IEEE80211_CIPHER_TKIP:
3562		printf("TKIP");
3563		break;
3564	case IEEE80211_CIPHER_AES_OCB:
3565		printf("AES-OCB");
3566		break;
3567	case IEEE80211_CIPHER_AES_CCM:
3568		printf("AES-CCM");
3569		break;
3570	case IEEE80211_CIPHER_CKIP:
3571		printf("CKIP");
3572		break;
3573	case IEEE80211_CIPHER_NONE:
3574		printf("NONE");
3575		break;
3576	default:
3577		printf("UNKNOWN (0x%x)", ireq->i_val);
3578		break;
3579	}
3580}
3581#endif
3582
3583static void
3584printkey(const struct ieee80211req_key *ik)
3585{
3586	static const uint8_t zerodata[IEEE80211_KEYBUF_SIZE];
3587	int keylen = ik->ik_keylen;
3588	int printcontents;
3589
3590	printcontents = printkeys &&
3591		(memcmp(ik->ik_keydata, zerodata, keylen) != 0 || verbose);
3592	if (printcontents)
3593		LINE_BREAK();
3594	switch (ik->ik_type) {
3595	case IEEE80211_CIPHER_WEP:
3596		/* compatibility */
3597		LINE_CHECK("wepkey %u:%s", ik->ik_keyix+1,
3598		    keylen <= 5 ? "40-bit" :
3599		    keylen <= 13 ? "104-bit" : "128-bit");
3600		break;
3601	case IEEE80211_CIPHER_TKIP:
3602		if (keylen > 128/8)
3603			keylen -= 128/8;	/* ignore MIC for now */
3604		LINE_CHECK("TKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
3605		break;
3606	case IEEE80211_CIPHER_AES_OCB:
3607		LINE_CHECK("AES-OCB %u:%u-bit", ik->ik_keyix+1, 8*keylen);
3608		break;
3609	case IEEE80211_CIPHER_AES_CCM:
3610		LINE_CHECK("AES-CCM %u:%u-bit", ik->ik_keyix+1, 8*keylen);
3611		break;
3612	case IEEE80211_CIPHER_CKIP:
3613		LINE_CHECK("CKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
3614		break;
3615	case IEEE80211_CIPHER_NONE:
3616		LINE_CHECK("NULL %u:%u-bit", ik->ik_keyix+1, 8*keylen);
3617		break;
3618	default:
3619		LINE_CHECK("UNKNOWN (0x%x) %u:%u-bit",
3620			ik->ik_type, ik->ik_keyix+1, 8*keylen);
3621		break;
3622	}
3623	if (printcontents) {
3624		int i;
3625
3626		printf(" <");
3627		for (i = 0; i < keylen; i++)
3628			printf("%02x", ik->ik_keydata[i]);
3629		printf(">");
3630		if (ik->ik_type != IEEE80211_CIPHER_WEP &&
3631		    (ik->ik_keyrsc != 0 || verbose))
3632			printf(" rsc %ju", (uintmax_t)ik->ik_keyrsc);
3633		if (ik->ik_type != IEEE80211_CIPHER_WEP &&
3634		    (ik->ik_keytsc != 0 || verbose))
3635			printf(" tsc %ju", (uintmax_t)ik->ik_keytsc);
3636		if (ik->ik_flags != 0 && verbose) {
3637			const char *sep = " ";
3638
3639			if (ik->ik_flags & IEEE80211_KEY_XMIT)
3640				printf("%stx", sep), sep = "+";
3641			if (ik->ik_flags & IEEE80211_KEY_RECV)
3642				printf("%srx", sep), sep = "+";
3643			if (ik->ik_flags & IEEE80211_KEY_DEFAULT)
3644				printf("%sdef", sep), sep = "+";
3645		}
3646		LINE_BREAK();
3647	}
3648}
3649
3650static void
3651printrate(const char *tag, int v, int defrate, int defmcs)
3652{
3653	if (v == 11)
3654		LINE_CHECK("%s 5.5", tag);
3655	else if (v & 0x80) {
3656		if (v != defmcs)
3657			LINE_CHECK("%s %d", tag, v &~ 0x80);
3658	} else {
3659		if (v != defrate)
3660			LINE_CHECK("%s %d", tag, v/2);
3661	}
3662}
3663
3664static int
3665getssid(int s, int ix, void *data, size_t len, int *plen)
3666{
3667	struct ieee80211req ireq;
3668
3669	(void) memset(&ireq, 0, sizeof(ireq));
3670	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
3671	ireq.i_type = IEEE80211_IOC_SSID;
3672	ireq.i_val = ix;
3673	ireq.i_data = data;
3674	ireq.i_len = len;
3675	if (ioctl(s, SIOCG80211, &ireq) < 0)
3676		return -1;
3677	*plen = ireq.i_len;
3678	return 0;
3679}
3680
3681static void
3682ieee80211_status(int s)
3683{
3684	static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
3685	enum ieee80211_opmode opmode = get80211opmode(s);
3686	int i, num, wpa, wme, bgscan, bgscaninterval, val, len, wepmode;
3687	uint8_t data[32];
3688	const struct ieee80211_channel *c;
3689	const struct ieee80211_roamparam *rp;
3690	const struct ieee80211_txparam *tp;
3691
3692	if (getssid(s, -1, data, sizeof(data), &len) < 0) {
3693		/* If we can't get the SSID, this isn't an 802.11 device. */
3694		return;
3695	}
3696
3697	/*
3698	 * Invalidate cached state so printing status for multiple
3699	 * if's doesn't reuse the first interfaces' cached state.
3700	 */
3701	gotcurchan = 0;
3702	gotroam = 0;
3703	gottxparams = 0;
3704	gothtconf = 0;
3705	gotregdomain = 0;
3706
3707	if (get80211val(s, IEEE80211_IOC_NUMSSIDS, &num) < 0)
3708		num = 0;
3709	printf("\tssid ");
3710	if (num > 1) {
3711		for (i = 0; i < num; i++) {
3712			if (getssid(s, i, data, sizeof(data), &len) >= 0 && len > 0) {
3713				printf(" %d:", i + 1);
3714				print_string(data, len);
3715			}
3716		}
3717	} else
3718		print_string(data, len);
3719
3720	c = getcurchan(s);
3721	if (c->ic_freq != IEEE80211_CHAN_ANY) {
3722		char buf[14];
3723		printf(" channel %d (%u Mhz%s)", c->ic_ieee, c->ic_freq,
3724			get_chaninfo(c, 1, buf, sizeof(buf)));
3725	} else if (verbose)
3726		printf(" channel UNDEF");
3727
3728	if (get80211(s, IEEE80211_IOC_BSSID, data, IEEE80211_ADDR_LEN) >= 0 &&
3729	    (memcmp(data, zerobssid, sizeof(zerobssid)) != 0 || verbose))
3730		printf(" bssid %s", ether_ntoa((struct ether_addr *)data));
3731
3732	if (get80211len(s, IEEE80211_IOC_STATIONNAME, data, sizeof(data), &len) != -1) {
3733		printf("\n\tstationname ");
3734		print_string(data, len);
3735	}
3736
3737	spacer = ' ';		/* force first break */
3738	LINE_BREAK();
3739
3740	list_regdomain(s, 0);
3741
3742	wpa = 0;
3743	if (get80211val(s, IEEE80211_IOC_AUTHMODE, &val) != -1) {
3744		switch (val) {
3745		case IEEE80211_AUTH_NONE:
3746			LINE_CHECK("authmode NONE");
3747			break;
3748		case IEEE80211_AUTH_OPEN:
3749			LINE_CHECK("authmode OPEN");
3750			break;
3751		case IEEE80211_AUTH_SHARED:
3752			LINE_CHECK("authmode SHARED");
3753			break;
3754		case IEEE80211_AUTH_8021X:
3755			LINE_CHECK("authmode 802.1x");
3756			break;
3757		case IEEE80211_AUTH_WPA:
3758			if (get80211val(s, IEEE80211_IOC_WPA, &wpa) < 0)
3759				wpa = 1;	/* default to WPA1 */
3760			switch (wpa) {
3761			case 2:
3762				LINE_CHECK("authmode WPA2/802.11i");
3763				break;
3764			case 3:
3765				LINE_CHECK("authmode WPA1+WPA2/802.11i");
3766				break;
3767			default:
3768				LINE_CHECK("authmode WPA");
3769				break;
3770			}
3771			break;
3772		case IEEE80211_AUTH_AUTO:
3773			LINE_CHECK("authmode AUTO");
3774			break;
3775		default:
3776			LINE_CHECK("authmode UNKNOWN (0x%x)", val);
3777			break;
3778		}
3779	}
3780
3781	if (wpa || verbose) {
3782		if (get80211val(s, IEEE80211_IOC_WPS, &val) != -1) {
3783			if (val)
3784				LINE_CHECK("wps");
3785			else if (verbose)
3786				LINE_CHECK("-wps");
3787		}
3788		if (get80211val(s, IEEE80211_IOC_TSN, &val) != -1) {
3789			if (val)
3790				LINE_CHECK("tsn");
3791			else if (verbose)
3792				LINE_CHECK("-tsn");
3793		}
3794		if (ioctl(s, IEEE80211_IOC_COUNTERMEASURES, &val) != -1) {
3795			if (val)
3796				LINE_CHECK("countermeasures");
3797			else if (verbose)
3798				LINE_CHECK("-countermeasures");
3799		}
3800#if 0
3801		/* XXX not interesting with WPA done in user space */
3802		ireq.i_type = IEEE80211_IOC_KEYMGTALGS;
3803		if (ioctl(s, SIOCG80211, &ireq) != -1) {
3804		}
3805
3806		ireq.i_type = IEEE80211_IOC_MCASTCIPHER;
3807		if (ioctl(s, SIOCG80211, &ireq) != -1) {
3808			LINE_CHECK("mcastcipher ");
3809			printcipher(s, &ireq, IEEE80211_IOC_MCASTKEYLEN);
3810			spacer = ' ';
3811		}
3812
3813		ireq.i_type = IEEE80211_IOC_UCASTCIPHER;
3814		if (ioctl(s, SIOCG80211, &ireq) != -1) {
3815			LINE_CHECK("ucastcipher ");
3816			printcipher(s, &ireq, IEEE80211_IOC_UCASTKEYLEN);
3817		}
3818
3819		if (wpa & 2) {
3820			ireq.i_type = IEEE80211_IOC_RSNCAPS;
3821			if (ioctl(s, SIOCG80211, &ireq) != -1) {
3822				LINE_CHECK("RSN caps 0x%x", ireq.i_val);
3823				spacer = ' ';
3824			}
3825		}
3826
3827		ireq.i_type = IEEE80211_IOC_UCASTCIPHERS;
3828		if (ioctl(s, SIOCG80211, &ireq) != -1) {
3829		}
3830#endif
3831	}
3832
3833	if (get80211val(s, IEEE80211_IOC_WEP, &wepmode) != -1 &&
3834	    wepmode != IEEE80211_WEP_NOSUP) {
3835		int firstkey;
3836
3837		switch (wepmode) {
3838		case IEEE80211_WEP_OFF:
3839			LINE_CHECK("privacy OFF");
3840			break;
3841		case IEEE80211_WEP_ON:
3842			LINE_CHECK("privacy ON");
3843			break;
3844		case IEEE80211_WEP_MIXED:
3845			LINE_CHECK("privacy MIXED");
3846			break;
3847		default:
3848			LINE_CHECK("privacy UNKNOWN (0x%x)", wepmode);
3849			break;
3850		}
3851
3852		/*
3853		 * If we get here then we've got WEP support so we need
3854		 * to print WEP status.
3855		 */
3856
3857		if (get80211val(s, IEEE80211_IOC_WEPTXKEY, &val) < 0) {
3858			warn("WEP support, but no tx key!");
3859			goto end;
3860		}
3861		if (val != -1)
3862			LINE_CHECK("deftxkey %d", val+1);
3863		else if (wepmode != IEEE80211_WEP_OFF || verbose)
3864			LINE_CHECK("deftxkey UNDEF");
3865
3866		if (get80211val(s, IEEE80211_IOC_NUMWEPKEYS, &num) < 0) {
3867			warn("WEP support, but no NUMWEPKEYS support!");
3868			goto end;
3869		}
3870
3871		firstkey = 1;
3872		for (i = 0; i < num; i++) {
3873			struct ieee80211req_key ik;
3874
3875			memset(&ik, 0, sizeof(ik));
3876			ik.ik_keyix = i;
3877			if (get80211(s, IEEE80211_IOC_WPAKEY, &ik, sizeof(ik)) < 0) {
3878				warn("WEP support, but can get keys!");
3879				goto end;
3880			}
3881			if (ik.ik_keylen != 0) {
3882				if (verbose)
3883					LINE_BREAK();
3884				printkey(&ik);
3885				firstkey = 0;
3886			}
3887		}
3888end:
3889		;
3890	}
3891
3892	if (get80211val(s, IEEE80211_IOC_POWERSAVE, &val) != -1 &&
3893	    val != IEEE80211_POWERSAVE_NOSUP ) {
3894		if (val != IEEE80211_POWERSAVE_OFF || verbose) {
3895			switch (val) {
3896			case IEEE80211_POWERSAVE_OFF:
3897				LINE_CHECK("powersavemode OFF");
3898				break;
3899			case IEEE80211_POWERSAVE_CAM:
3900				LINE_CHECK("powersavemode CAM");
3901				break;
3902			case IEEE80211_POWERSAVE_PSP:
3903				LINE_CHECK("powersavemode PSP");
3904				break;
3905			case IEEE80211_POWERSAVE_PSP_CAM:
3906				LINE_CHECK("powersavemode PSP-CAM");
3907				break;
3908			}
3909			if (get80211val(s, IEEE80211_IOC_POWERSAVESLEEP, &val) != -1)
3910				LINE_CHECK("powersavesleep %d", val);
3911		}
3912	}
3913
3914	if (get80211val(s, IEEE80211_IOC_TXPOWER, &val) != -1) {
3915		if (val & 1)
3916			LINE_CHECK("txpower %d.5", val/2);
3917		else
3918			LINE_CHECK("txpower %d", val/2);
3919	}
3920	if (verbose) {
3921		if (get80211val(s, IEEE80211_IOC_TXPOWMAX, &val) != -1)
3922			LINE_CHECK("txpowmax %.1f", val/2.);
3923	}
3924
3925	if (get80211val(s, IEEE80211_IOC_DOTD, &val) != -1) {
3926		if (val)
3927			LINE_CHECK("dotd");
3928		else if (verbose)
3929			LINE_CHECK("-dotd");
3930	}
3931
3932	if (get80211val(s, IEEE80211_IOC_RTSTHRESHOLD, &val) != -1) {
3933		if (val != IEEE80211_RTS_MAX || verbose)
3934			LINE_CHECK("rtsthreshold %d", val);
3935	}
3936
3937	if (get80211val(s, IEEE80211_IOC_FRAGTHRESHOLD, &val) != -1) {
3938		if (val != IEEE80211_FRAG_MAX || verbose)
3939			LINE_CHECK("fragthreshold %d", val);
3940	}
3941	if (opmode == IEEE80211_M_STA || verbose) {
3942		if (get80211val(s, IEEE80211_IOC_BMISSTHRESHOLD, &val) != -1) {
3943			if (val != IEEE80211_HWBMISS_MAX || verbose)
3944				LINE_CHECK("bmiss %d", val);
3945		}
3946	}
3947
3948	if (!verbose) {
3949		gettxparams(s);
3950		tp = &txparams.params[chan2mode(c)];
3951		printrate("ucastrate", tp->ucastrate,
3952		    IEEE80211_FIXED_RATE_NONE, IEEE80211_FIXED_RATE_NONE);
3953		printrate("mcastrate", tp->mcastrate, 2*1, 0x80|0);
3954		printrate("mgmtrate", tp->mgmtrate, 2*1, 0x80|0);
3955		if (tp->maxretry != 6)		/* XXX */
3956			LINE_CHECK("maxretry %d", tp->maxretry);
3957	} else {
3958		LINE_BREAK();
3959		list_txparams(s);
3960	}
3961
3962	bgscaninterval = -1;
3963	(void) get80211val(s, IEEE80211_IOC_BGSCAN_INTERVAL, &bgscaninterval);
3964
3965	if (get80211val(s, IEEE80211_IOC_SCANVALID, &val) != -1) {
3966		if (val != bgscaninterval || verbose)
3967			LINE_CHECK("scanvalid %u", val);
3968	}
3969
3970	bgscan = 0;
3971	if (get80211val(s, IEEE80211_IOC_BGSCAN, &bgscan) != -1) {
3972		if (bgscan)
3973			LINE_CHECK("bgscan");
3974		else if (verbose)
3975			LINE_CHECK("-bgscan");
3976	}
3977	if (bgscan || verbose) {
3978		if (bgscaninterval != -1)
3979			LINE_CHECK("bgscanintvl %u", bgscaninterval);
3980		if (get80211val(s, IEEE80211_IOC_BGSCAN_IDLE, &val) != -1)
3981			LINE_CHECK("bgscanidle %u", val);
3982		if (!verbose) {
3983			getroam(s);
3984			rp = &roamparams.params[chan2mode(c)];
3985			if (rp->rssi & 1)
3986				LINE_CHECK("roam:rssi %u.5", rp->rssi/2);
3987			else
3988				LINE_CHECK("roam:rssi %u", rp->rssi/2);
3989			LINE_CHECK("roam:rate %u", rp->rate/2);
3990		} else {
3991			LINE_BREAK();
3992			list_roam(s);
3993		}
3994	}
3995
3996	if (IEEE80211_IS_CHAN_ANYG(c) || verbose) {
3997		if (get80211val(s, IEEE80211_IOC_PUREG, &val) != -1) {
3998			if (val)
3999				LINE_CHECK("pureg");
4000			else if (verbose)
4001				LINE_CHECK("-pureg");
4002		}
4003		if (get80211val(s, IEEE80211_IOC_PROTMODE, &val) != -1) {
4004			switch (val) {
4005			case IEEE80211_PROTMODE_OFF:
4006				LINE_CHECK("protmode OFF");
4007				break;
4008			case IEEE80211_PROTMODE_CTS:
4009				LINE_CHECK("protmode CTS");
4010				break;
4011			case IEEE80211_PROTMODE_RTSCTS:
4012				LINE_CHECK("protmode RTSCTS");
4013				break;
4014			default:
4015				LINE_CHECK("protmode UNKNOWN (0x%x)", val);
4016				break;
4017			}
4018		}
4019	}
4020
4021	if (IEEE80211_IS_CHAN_HT(c) || verbose) {
4022		gethtconf(s);
4023		switch (htconf & 3) {
4024		case 0:
4025		case 2:
4026			LINE_CHECK("-ht");
4027			break;
4028		case 1:
4029			LINE_CHECK("ht20");
4030			break;
4031		case 3:
4032			if (verbose)
4033				LINE_CHECK("ht");
4034			break;
4035		}
4036		if (get80211val(s, IEEE80211_IOC_HTCOMPAT, &val) != -1) {
4037			if (!val)
4038				LINE_CHECK("-htcompat");
4039			else if (verbose)
4040				LINE_CHECK("htcompat");
4041		}
4042		if (get80211val(s, IEEE80211_IOC_AMPDU, &val) != -1) {
4043			switch (val) {
4044			case 0:
4045				LINE_CHECK("-ampdu");
4046				break;
4047			case 1:
4048				LINE_CHECK("ampdutx -ampdurx");
4049				break;
4050			case 2:
4051				LINE_CHECK("-ampdutx ampdurx");
4052				break;
4053			case 3:
4054				if (verbose)
4055					LINE_CHECK("ampdu");
4056				break;
4057			}
4058		}
4059		if (get80211val(s, IEEE80211_IOC_AMPDU_LIMIT, &val) != -1) {
4060			switch (val) {
4061			case IEEE80211_HTCAP_MAXRXAMPDU_8K:
4062				LINE_CHECK("ampdulimit 8k");
4063				break;
4064			case IEEE80211_HTCAP_MAXRXAMPDU_16K:
4065				LINE_CHECK("ampdulimit 16k");
4066				break;
4067			case IEEE80211_HTCAP_MAXRXAMPDU_32K:
4068				LINE_CHECK("ampdulimit 32k");
4069				break;
4070			case IEEE80211_HTCAP_MAXRXAMPDU_64K:
4071				LINE_CHECK("ampdulimit 64k");
4072				break;
4073			}
4074		}
4075		if (get80211val(s, IEEE80211_IOC_AMPDU_DENSITY, &val) != -1) {
4076			switch (val) {
4077			case IEEE80211_HTCAP_MPDUDENSITY_NA:
4078				if (verbose)
4079					LINE_CHECK("ampdudensity NA");
4080				break;
4081			case IEEE80211_HTCAP_MPDUDENSITY_025:
4082				LINE_CHECK("ampdudensity .25");
4083				break;
4084			case IEEE80211_HTCAP_MPDUDENSITY_05:
4085				LINE_CHECK("ampdudensity .5");
4086				break;
4087			case IEEE80211_HTCAP_MPDUDENSITY_1:
4088				LINE_CHECK("ampdudensity 1");
4089				break;
4090			case IEEE80211_HTCAP_MPDUDENSITY_2:
4091				LINE_CHECK("ampdudensity 2");
4092				break;
4093			case IEEE80211_HTCAP_MPDUDENSITY_4:
4094				LINE_CHECK("ampdudensity 4");
4095				break;
4096			case IEEE80211_HTCAP_MPDUDENSITY_8:
4097				LINE_CHECK("ampdudensity 8");
4098				break;
4099			case IEEE80211_HTCAP_MPDUDENSITY_16:
4100				LINE_CHECK("ampdudensity 16");
4101				break;
4102			}
4103		}
4104		if (get80211val(s, IEEE80211_IOC_AMSDU, &val) != -1) {
4105			switch (val) {
4106			case 0:
4107				LINE_CHECK("-amsdu");
4108				break;
4109			case 1:
4110				LINE_CHECK("amsdutx -amsdurx");
4111				break;
4112			case 2:
4113				LINE_CHECK("-amsdutx amsdurx");
4114				break;
4115			case 3:
4116				if (verbose)
4117					LINE_CHECK("amsdu");
4118				break;
4119			}
4120		}
4121		/* XXX amsdu limit */
4122		if (get80211val(s, IEEE80211_IOC_SHORTGI, &val) != -1) {
4123			if (val)
4124				LINE_CHECK("shortgi");
4125			else if (verbose)
4126				LINE_CHECK("-shortgi");
4127		}
4128		if (get80211val(s, IEEE80211_IOC_HTPROTMODE, &val) != -1) {
4129			if (val == IEEE80211_PROTMODE_OFF)
4130				LINE_CHECK("htprotmode OFF");
4131			else if (val != IEEE80211_PROTMODE_RTSCTS)
4132				LINE_CHECK("htprotmode UNKNOWN (0x%x)", val);
4133			else if (verbose)
4134				LINE_CHECK("htprotmode RTSCTS");
4135		}
4136		if (get80211val(s, IEEE80211_IOC_PUREN, &val) != -1) {
4137			if (val)
4138				LINE_CHECK("puren");
4139			else if (verbose)
4140				LINE_CHECK("-puren");
4141		}
4142		if (get80211val(s, IEEE80211_IOC_SMPS, &val) != -1) {
4143			if (val == IEEE80211_HTCAP_SMPS_DYNAMIC)
4144				LINE_CHECK("smpsdyn");
4145			else if (val == IEEE80211_HTCAP_SMPS_ENA)
4146				LINE_CHECK("smps");
4147			else if (verbose)
4148				LINE_CHECK("-smps");
4149		}
4150		if (get80211val(s, IEEE80211_IOC_RIFS, &val) != -1) {
4151			if (val)
4152				LINE_CHECK("rifs");
4153			else if (verbose)
4154				LINE_CHECK("-rifs");
4155		}
4156	}
4157
4158	if (get80211val(s, IEEE80211_IOC_WME, &wme) != -1) {
4159		if (wme)
4160			LINE_CHECK("wme");
4161		else if (verbose)
4162			LINE_CHECK("-wme");
4163	} else
4164		wme = 0;
4165
4166	if (get80211val(s, IEEE80211_IOC_BURST, &val) != -1) {
4167		if (val)
4168			LINE_CHECK("burst");
4169		else if (verbose)
4170			LINE_CHECK("-burst");
4171	}
4172
4173	if (get80211val(s, IEEE80211_IOC_FF, &val) != -1) {
4174		if (val)
4175			LINE_CHECK("ff");
4176		else if (verbose)
4177			LINE_CHECK("-ff");
4178	}
4179	if (get80211val(s, IEEE80211_IOC_TURBOP, &val) != -1) {
4180		if (val)
4181			LINE_CHECK("dturbo");
4182		else if (verbose)
4183			LINE_CHECK("-dturbo");
4184	}
4185	if (get80211val(s, IEEE80211_IOC_DWDS, &val) != -1) {
4186		if (val)
4187			LINE_CHECK("dwds");
4188		else if (verbose)
4189			LINE_CHECK("-dwds");
4190	}
4191
4192	if (opmode == IEEE80211_M_HOSTAP) {
4193		if (get80211val(s, IEEE80211_IOC_HIDESSID, &val) != -1) {
4194			if (val)
4195				LINE_CHECK("hidessid");
4196			else if (verbose)
4197				LINE_CHECK("-hidessid");
4198		}
4199		if (get80211val(s, IEEE80211_IOC_APBRIDGE, &val) != -1) {
4200			if (!val)
4201				LINE_CHECK("-apbridge");
4202			else if (verbose)
4203				LINE_CHECK("apbridge");
4204		}
4205		if (get80211val(s, IEEE80211_IOC_DTIM_PERIOD, &val) != -1)
4206			LINE_CHECK("dtimperiod %u", val);
4207
4208		if (get80211val(s, IEEE80211_IOC_DOTH, &val) != -1) {
4209			if (!val)
4210				LINE_CHECK("-doth");
4211			else if (verbose)
4212				LINE_CHECK("doth");
4213		}
4214		if (get80211val(s, IEEE80211_IOC_DFS, &val) != -1) {
4215			if (!val)
4216				LINE_CHECK("-dfs");
4217			else if (verbose)
4218				LINE_CHECK("dfs");
4219		}
4220		if (get80211val(s, IEEE80211_IOC_INACTIVITY, &val) != -1) {
4221			if (!val)
4222				LINE_CHECK("-inact");
4223			else if (verbose)
4224				LINE_CHECK("inact");
4225		}
4226	} else {
4227		if (get80211val(s, IEEE80211_IOC_ROAMING, &val) != -1) {
4228			if (val != IEEE80211_ROAMING_AUTO || verbose) {
4229				switch (val) {
4230				case IEEE80211_ROAMING_DEVICE:
4231					LINE_CHECK("roaming DEVICE");
4232					break;
4233				case IEEE80211_ROAMING_AUTO:
4234					LINE_CHECK("roaming AUTO");
4235					break;
4236				case IEEE80211_ROAMING_MANUAL:
4237					LINE_CHECK("roaming MANUAL");
4238					break;
4239				default:
4240					LINE_CHECK("roaming UNKNOWN (0x%x)",
4241						val);
4242					break;
4243				}
4244			}
4245		}
4246	}
4247	if (get80211val(s, IEEE80211_IOC_BEACON_INTERVAL, &val) != -1) {
4248		/* XXX default define not visible */
4249		if (val != 100 || verbose)
4250			LINE_CHECK("bintval %u", val);
4251	}
4252
4253	if (wme && verbose) {
4254		LINE_BREAK();
4255		list_wme(s);
4256	}
4257	LINE_BREAK();
4258}
4259
4260static int
4261get80211(int s, int type, void *data, int len)
4262{
4263	struct ieee80211req ireq;
4264
4265	(void) memset(&ireq, 0, sizeof(ireq));
4266	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4267	ireq.i_type = type;
4268	ireq.i_data = data;
4269	ireq.i_len = len;
4270	return ioctl(s, SIOCG80211, &ireq);
4271}
4272
4273static int
4274get80211len(int s, int type, void *data, int len, int *plen)
4275{
4276	struct ieee80211req ireq;
4277
4278	(void) memset(&ireq, 0, sizeof(ireq));
4279	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4280	ireq.i_type = type;
4281	ireq.i_len = len;
4282	ireq.i_data = data;
4283	if (ioctl(s, SIOCG80211, &ireq) < 0)
4284		return -1;
4285	*plen = ireq.i_len;
4286	return 0;
4287}
4288
4289static int
4290get80211val(int s, int type, int *val)
4291{
4292	struct ieee80211req ireq;
4293
4294	(void) memset(&ireq, 0, sizeof(ireq));
4295	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4296	ireq.i_type = type;
4297	if (ioctl(s, SIOCG80211, &ireq) < 0)
4298		return -1;
4299	*val = ireq.i_val;
4300	return 0;
4301}
4302
4303static void
4304set80211(int s, int type, int val, int len, void *data)
4305{
4306	struct ieee80211req	ireq;
4307
4308	(void) memset(&ireq, 0, sizeof(ireq));
4309	(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
4310	ireq.i_type = type;
4311	ireq.i_val = val;
4312	ireq.i_len = len;
4313	ireq.i_data = data;
4314	if (ioctl(s, SIOCS80211, &ireq) < 0)
4315		err(1, "SIOCS80211");
4316}
4317
4318static const char *
4319get_string(const char *val, const char *sep, u_int8_t *buf, int *lenp)
4320{
4321	int len;
4322	int hexstr;
4323	u_int8_t *p;
4324
4325	len = *lenp;
4326	p = buf;
4327	hexstr = (val[0] == '0' && tolower((u_char)val[1]) == 'x');
4328	if (hexstr)
4329		val += 2;
4330	for (;;) {
4331		if (*val == '\0')
4332			break;
4333		if (sep != NULL && strchr(sep, *val) != NULL) {
4334			val++;
4335			break;
4336		}
4337		if (hexstr) {
4338			if (!isxdigit((u_char)val[0])) {
4339				warnx("bad hexadecimal digits");
4340				return NULL;
4341			}
4342			if (!isxdigit((u_char)val[1])) {
4343				warnx("odd count hexadecimal digits");
4344				return NULL;
4345			}
4346		}
4347		if (p >= buf + len) {
4348			if (hexstr)
4349				warnx("hexadecimal digits too long");
4350			else
4351				warnx("string too long");
4352			return NULL;
4353		}
4354		if (hexstr) {
4355#define	tohex(x)	(isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
4356			*p++ = (tohex((u_char)val[0]) << 4) |
4357			    tohex((u_char)val[1]);
4358#undef tohex
4359			val += 2;
4360		} else
4361			*p++ = *val++;
4362	}
4363	len = p - buf;
4364	/* The string "-" is treated as the empty string. */
4365	if (!hexstr && len == 1 && buf[0] == '-') {
4366		len = 0;
4367		memset(buf, 0, *lenp);
4368	} else if (len < *lenp)
4369		memset(p, 0, *lenp - len);
4370	*lenp = len;
4371	return val;
4372}
4373
4374static void
4375print_string(const u_int8_t *buf, int len)
4376{
4377	int i;
4378	int hasspc;
4379
4380	i = 0;
4381	hasspc = 0;
4382	for (; i < len; i++) {
4383		if (!isprint(buf[i]) && buf[i] != '\0')
4384			break;
4385		if (isspace(buf[i]))
4386			hasspc++;
4387	}
4388	if (i == len) {
4389		if (hasspc || len == 0 || buf[0] == '\0')
4390			printf("\"%.*s\"", len, buf);
4391		else
4392			printf("%.*s", len, buf);
4393	} else {
4394		printf("0x");
4395		for (i = 0; i < len; i++)
4396			printf("%02x", buf[i]);
4397	}
4398}
4399
4400/*
4401 * Virtual AP cloning support.
4402 */
4403static struct ieee80211_clone_params params = {
4404	.icp_opmode	= IEEE80211_M_STA,	/* default to station mode */
4405};
4406
4407static void
4408wlan_create(int s, struct ifreq *ifr)
4409{
4410	static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
4411
4412	if (params.icp_parent[0] == '\0')
4413		errx(1, "must specify a parent when creating a wlan device");
4414	if (params.icp_opmode == IEEE80211_M_WDS &&
4415	    memcmp(params.icp_bssid, zerobssid, sizeof(zerobssid)) == 0)
4416		errx(1, "no bssid specified for WDS (use wlanbssid)");
4417	ifr->ifr_data = (caddr_t) &params;
4418	if (ioctl(s, SIOCIFCREATE2, ifr) < 0)
4419		err(1, "SIOCIFCREATE2");
4420}
4421
4422static
4423DECL_CMD_FUNC(set80211clone_wlandev, arg, d)
4424{
4425	strlcpy(params.icp_parent, arg, IFNAMSIZ);
4426	clone_setcallback(wlan_create);
4427}
4428
4429static
4430DECL_CMD_FUNC(set80211clone_wlanbssid, arg, d)
4431{
4432	const struct ether_addr *ea;
4433
4434	ea = ether_aton(arg);
4435	if (ea == NULL)
4436		errx(1, "%s: cannot parse bssid", arg);
4437	memcpy(params.icp_bssid, ea->octet, IEEE80211_ADDR_LEN);
4438	clone_setcallback(wlan_create);
4439}
4440
4441static
4442DECL_CMD_FUNC(set80211clone_wlanaddr, 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 addres", arg);
4449	memcpy(params.icp_macaddr, ea->octet, IEEE80211_ADDR_LEN);
4450	params.icp_flags |= IEEE80211_CLONE_MACADDR;
4451	clone_setcallback(wlan_create);
4452}
4453
4454static
4455DECL_CMD_FUNC(set80211clone_wlanmode, arg, d)
4456{
4457#define	iseq(a,b)	(strncasecmp(a,b,sizeof(b)-1) == 0)
4458	if (iseq(arg, "sta"))
4459		params.icp_opmode = IEEE80211_M_STA;
4460	else if (iseq(arg, "ahdemo") || iseq(arg, "adhoc-demo"))
4461		params.icp_opmode = IEEE80211_M_AHDEMO;
4462	else if (iseq(arg, "ibss") || iseq(arg, "adhoc"))
4463		params.icp_opmode = IEEE80211_M_IBSS;
4464	else if (iseq(arg, "ap") || iseq(arg, "host"))
4465		params.icp_opmode = IEEE80211_M_HOSTAP;
4466	else if (iseq(arg, "wds"))
4467		params.icp_opmode = IEEE80211_M_WDS;
4468	else if (iseq(arg, "monitor"))
4469		params.icp_opmode = IEEE80211_M_MONITOR;
4470	else
4471		errx(1, "Don't know to create %s for %s", arg, name);
4472	clone_setcallback(wlan_create);
4473#undef iseq
4474}
4475
4476static void
4477set80211clone_beacons(const char *val, int d, int s, const struct afswtch *rafp)
4478{
4479	/* NB: inverted sense */
4480	if (d)
4481		params.icp_flags &= ~IEEE80211_CLONE_NOBEACONS;
4482	else
4483		params.icp_flags |= IEEE80211_CLONE_NOBEACONS;
4484	clone_setcallback(wlan_create);
4485}
4486
4487static void
4488set80211clone_bssid(const char *val, int d, int s, const struct afswtch *rafp)
4489{
4490	if (d)
4491		params.icp_flags |= IEEE80211_CLONE_BSSID;
4492	else
4493		params.icp_flags &= ~IEEE80211_CLONE_BSSID;
4494	clone_setcallback(wlan_create);
4495}
4496
4497static void
4498set80211clone_wdslegacy(const char *val, int d, int s, const struct afswtch *rafp)
4499{
4500	if (d)
4501		params.icp_flags |= IEEE80211_CLONE_WDSLEGACY;
4502	else
4503		params.icp_flags &= ~IEEE80211_CLONE_WDSLEGACY;
4504	clone_setcallback(wlan_create);
4505}
4506
4507static struct cmd ieee80211_cmds[] = {
4508	DEF_CMD_ARG("ssid",		set80211ssid),
4509	DEF_CMD_ARG("nwid",		set80211ssid),
4510	DEF_CMD_ARG("stationname",	set80211stationname),
4511	DEF_CMD_ARG("station",		set80211stationname),	/* BSD/OS */
4512	DEF_CMD_ARG("channel",		set80211channel),
4513	DEF_CMD_ARG("authmode",		set80211authmode),
4514	DEF_CMD_ARG("powersavemode",	set80211powersavemode),
4515	DEF_CMD("powersave",	1,	set80211powersave),
4516	DEF_CMD("-powersave",	0,	set80211powersave),
4517	DEF_CMD_ARG("powersavesleep", 	set80211powersavesleep),
4518	DEF_CMD_ARG("wepmode",		set80211wepmode),
4519	DEF_CMD("wep",		1,	set80211wep),
4520	DEF_CMD("-wep",		0,	set80211wep),
4521	DEF_CMD_ARG("deftxkey",		set80211weptxkey),
4522	DEF_CMD_ARG("weptxkey",		set80211weptxkey),
4523	DEF_CMD_ARG("wepkey",		set80211wepkey),
4524	DEF_CMD_ARG("nwkey",		set80211nwkey),		/* NetBSD */
4525	DEF_CMD("-nwkey",	0,	set80211wep),		/* NetBSD */
4526	DEF_CMD_ARG("rtsthreshold",	set80211rtsthreshold),
4527	DEF_CMD_ARG("protmode",		set80211protmode),
4528	DEF_CMD_ARG("txpower",		set80211txpower),
4529	DEF_CMD_ARG("roaming",		set80211roaming),
4530	DEF_CMD("wme",		1,	set80211wme),
4531	DEF_CMD("-wme",		0,	set80211wme),
4532	DEF_CMD("wmm",		1,	set80211wme),
4533	DEF_CMD("-wmm",		0,	set80211wme),
4534	DEF_CMD("hidessid",	1,	set80211hidessid),
4535	DEF_CMD("-hidessid",	0,	set80211hidessid),
4536	DEF_CMD("apbridge",	1,	set80211apbridge),
4537	DEF_CMD("-apbridge",	0,	set80211apbridge),
4538	DEF_CMD_ARG("chanlist",		set80211chanlist),
4539	DEF_CMD_ARG("bssid",		set80211bssid),
4540	DEF_CMD_ARG("ap",		set80211bssid),
4541	DEF_CMD("scan",	0,		set80211scan),
4542	DEF_CMD_ARG("list",		set80211list),
4543	DEF_CMD_ARG2("cwmin",		set80211cwmin),
4544	DEF_CMD_ARG2("cwmax",		set80211cwmax),
4545	DEF_CMD_ARG2("aifs",		set80211aifs),
4546	DEF_CMD_ARG2("txoplimit",	set80211txoplimit),
4547	DEF_CMD_ARG("acm",		set80211acm),
4548	DEF_CMD_ARG("-acm",		set80211noacm),
4549	DEF_CMD_ARG("ack",		set80211ackpolicy),
4550	DEF_CMD_ARG("-ack",		set80211noackpolicy),
4551	DEF_CMD_ARG2("bss:cwmin",	set80211bsscwmin),
4552	DEF_CMD_ARG2("bss:cwmax",	set80211bsscwmax),
4553	DEF_CMD_ARG2("bss:aifs",	set80211bssaifs),
4554	DEF_CMD_ARG2("bss:txoplimit",	set80211bsstxoplimit),
4555	DEF_CMD_ARG("dtimperiod",	set80211dtimperiod),
4556	DEF_CMD_ARG("bintval",		set80211bintval),
4557	DEF_CMD("mac:open",	IEEE80211_MACCMD_POLICY_OPEN,	set80211maccmd),
4558	DEF_CMD("mac:allow",	IEEE80211_MACCMD_POLICY_ALLOW,	set80211maccmd),
4559	DEF_CMD("mac:deny",	IEEE80211_MACCMD_POLICY_DENY,	set80211maccmd),
4560	DEF_CMD("mac:radius",	IEEE80211_MACCMD_POLICY_RADIUS,	set80211maccmd),
4561	DEF_CMD("mac:flush",	IEEE80211_MACCMD_FLUSH,		set80211maccmd),
4562	DEF_CMD("mac:detach",	IEEE80211_MACCMD_DETACH,	set80211maccmd),
4563	DEF_CMD_ARG("mac:add",		set80211addmac),
4564	DEF_CMD_ARG("mac:del",		set80211delmac),
4565	DEF_CMD_ARG("mac:kick",		set80211kickmac),
4566	DEF_CMD("pureg",	1,	set80211pureg),
4567	DEF_CMD("-pureg",	0,	set80211pureg),
4568	DEF_CMD("ff",		1,	set80211fastframes),
4569	DEF_CMD("-ff",		0,	set80211fastframes),
4570	DEF_CMD("dturbo",	1,	set80211dturbo),
4571	DEF_CMD("-dturbo",	0,	set80211dturbo),
4572	DEF_CMD("bgscan",	1,	set80211bgscan),
4573	DEF_CMD("-bgscan",	0,	set80211bgscan),
4574	DEF_CMD_ARG("bgscanidle",	set80211bgscanidle),
4575	DEF_CMD_ARG("bgscanintvl",	set80211bgscanintvl),
4576	DEF_CMD_ARG("scanvalid",	set80211scanvalid),
4577	DEF_CMD_ARG("roam:rssi",	set80211roamrssi),
4578	DEF_CMD_ARG("roam:rate",	set80211roamrate),
4579	DEF_CMD_ARG("mcastrate",	set80211mcastrate),
4580	DEF_CMD_ARG("ucastrate",	set80211ucastrate),
4581	DEF_CMD_ARG("mgtrate",		set80211mgtrate),
4582	DEF_CMD_ARG("mgmtrate",		set80211mgtrate),
4583	DEF_CMD_ARG("maxretry",		set80211maxretry),
4584	DEF_CMD_ARG("fragthreshold",	set80211fragthreshold),
4585	DEF_CMD("burst",	1,	set80211burst),
4586	DEF_CMD("-burst",	0,	set80211burst),
4587	DEF_CMD_ARG("bmiss",		set80211bmissthreshold),
4588	DEF_CMD_ARG("bmissthreshold",	set80211bmissthreshold),
4589	DEF_CMD("shortgi",	1,	set80211shortgi),
4590	DEF_CMD("-shortgi",	0,	set80211shortgi),
4591	DEF_CMD("ampdurx",	2,	set80211ampdu),
4592	DEF_CMD("-ampdurx",	-2,	set80211ampdu),
4593	DEF_CMD("ampdutx",	1,	set80211ampdu),
4594	DEF_CMD("-ampdutx",	-1,	set80211ampdu),
4595	DEF_CMD("ampdu",	3,	set80211ampdu),		/* NB: tx+rx */
4596	DEF_CMD("-ampdu",	-3,	set80211ampdu),
4597	DEF_CMD_ARG("ampdulimit",	set80211ampdulimit),
4598	DEF_CMD_ARG("ampdudensity",	set80211ampdudensity),
4599	DEF_CMD("amsdurx",	2,	set80211amsdu),
4600	DEF_CMD("-amsdurx",	-2,	set80211amsdu),
4601	DEF_CMD("amsdutx",	1,	set80211amsdu),
4602	DEF_CMD("-amsdutx",	-1,	set80211amsdu),
4603	DEF_CMD("amsdu",	3,	set80211amsdu),		/* NB: tx+rx */
4604	DEF_CMD("-amsdu",	-3,	set80211amsdu),
4605	DEF_CMD_ARG("amsdulimit",	set80211amsdulimit),
4606	DEF_CMD("puren",	1,	set80211puren),
4607	DEF_CMD("-puren",	0,	set80211puren),
4608	DEF_CMD("doth",		1,	set80211doth),
4609	DEF_CMD("-doth",	0,	set80211doth),
4610	DEF_CMD("dfs",		1,	set80211dfs),
4611	DEF_CMD("-dfs",		0,	set80211dfs),
4612	DEF_CMD("htcompat",	1,	set80211htcompat),
4613	DEF_CMD("-htcompat",	0,	set80211htcompat),
4614	DEF_CMD("dwds",		1,	set80211dwds),
4615	DEF_CMD("-dwds",	0,	set80211dwds),
4616	DEF_CMD("inact",	1,	set80211inact),
4617	DEF_CMD("-inact",	0,	set80211inact),
4618	DEF_CMD("tsn",		1,	set80211tsn),
4619	DEF_CMD("-tsn",		0,	set80211tsn),
4620	DEF_CMD_ARG("regdomain",	set80211regdomain),
4621	DEF_CMD_ARG("country",		set80211country),
4622	DEF_CMD("indoor",	'I',	set80211location),
4623	DEF_CMD("-indoor",	'O',	set80211location),
4624	DEF_CMD("outdoor",	'O',	set80211location),
4625	DEF_CMD("-outdoor",	'I',	set80211location),
4626	DEF_CMD("anywhere",	' ',	set80211location),
4627	DEF_CMD("ecm",		1,	set80211ecm),
4628	DEF_CMD("-ecm",		0,	set80211ecm),
4629	DEF_CMD("dotd",		1,	set80211dotd),
4630	DEF_CMD("-dotd",	0,	set80211dotd),
4631	DEF_CMD_ARG("htprotmode",	set80211htprotmode),
4632	DEF_CMD("ht20",		1,	set80211htconf),
4633	DEF_CMD("-ht20",	0,	set80211htconf),
4634	DEF_CMD("ht40",		3,	set80211htconf),	/* NB: 20+40 */
4635	DEF_CMD("-ht40",	0,	set80211htconf),
4636	DEF_CMD("ht",		3,	set80211htconf),	/* NB: 20+40 */
4637	DEF_CMD("-ht",		0,	set80211htconf),
4638	DEF_CMD("rifs",		1,	set80211rifs),
4639	DEF_CMD("-rifs",	0,	set80211rifs),
4640	DEF_CMD("smps",		IEEE80211_HTCAP_SMPS_ENA,	set80211smps),
4641	DEF_CMD("smpsdyn",	IEEE80211_HTCAP_SMPS_DYNAMIC,	set80211smps),
4642	DEF_CMD("-smps",	IEEE80211_HTCAP_SMPS_OFF,	set80211smps),
4643	/* XXX for testing */
4644	DEF_CMD_ARG("chanswitch",	set80211chanswitch),
4645
4646	/* vap cloning support */
4647	DEF_CLONE_CMD_ARG("wlanaddr",	set80211clone_wlanaddr),
4648	DEF_CLONE_CMD_ARG("wlanbssid",	set80211clone_wlanbssid),
4649	DEF_CLONE_CMD_ARG("wlandev",	set80211clone_wlandev),
4650	DEF_CLONE_CMD_ARG("wlanmode",	set80211clone_wlanmode),
4651	DEF_CLONE_CMD("beacons", 1,	set80211clone_beacons),
4652	DEF_CLONE_CMD("-beacons", 0,	set80211clone_beacons),
4653	DEF_CLONE_CMD("bssid",	1,	set80211clone_bssid),
4654	DEF_CLONE_CMD("-bssid",	0,	set80211clone_bssid),
4655	DEF_CLONE_CMD("wdslegacy", 1,	set80211clone_wdslegacy),
4656	DEF_CLONE_CMD("-wdslegacy", 0,	set80211clone_wdslegacy),
4657};
4658static struct afswtch af_ieee80211 = {
4659	.af_name	= "af_ieee80211",
4660	.af_af		= AF_UNSPEC,
4661	.af_other_status = ieee80211_status,
4662};
4663
4664static __constructor void
4665ieee80211_ctor(void)
4666{
4667#define	N(a)	(sizeof(a) / sizeof(a[0]))
4668	int i;
4669
4670	for (i = 0; i < N(ieee80211_cmds);  i++)
4671		cmd_register(&ieee80211_cmds[i]);
4672	af_register(&af_ieee80211);
4673#undef N
4674}
4675