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